如何在#34;"中打印变量?

时间:2015-10-17 02:44:09

标签: python python-3.x

如何在""中打印变量? 例如;

a = "test"
print"this is a (how do I input 'a' here?)"

3 个答案:

答案 0 :(得分:4)

您应该阅读打印tutorial

但你要做的是:

print("this is a {} here?".format(a))

如果您想在字符串中放置多个变量,可以这样做:

print("this is a {0} here and {1} and also {2}?".format(a, b, c))

您实际上可以在没有数字规范的情况下编写这样的行:

print("this is a {} here and {} and also {}?".format(a, b, c))

如果你想在字符串中重新排序参数的位置,那么明确数字是最好的,如下所示:

print("this is a {2} here and {0} and also {1}?".format(a, b, c))

所以,在上面的例子中,第一个字符串是c,然后是a,然后是b。

对于您尝试在字符串中添加引号的特定情况,有不同的方法可以执行此操作。如果你想要双引号,你可以用单引号包装:

print('this is a "{2}" here and "{0}" and also "{1}"?'.format(a, b, c))

如果你想要单引号,请用双引号括起来:

print("this is a '{2}' here and '{0}' and also '{1}'?".format(a, b, c))

最后,还有三重单引号:

print('''this is a '{2}' here and '{0}' and also '{1}'?'''.format(a, b, c))

混合任何类型的引用:

print('''this is a "{2}" here and "{0}" and also '{1}'?'''.format(a, b, c))

答案 1 :(得分:0)

使用(Python 3)

print("this is a (how do I input ", a , "here?)")

请参阅:https://docs.python.org/3.0/whatsnew/3.0.html

旧版本使用

print "this is a (how do I input '%s' here?)" % a

请参阅http://learnpythonthehardway.org/book/ex5.html

答案 2 :(得分:0)

您可以使用加号运算符:

a = "test"
print"this is a " + a

请参阅:https://pythonspot.com/python-strings/