Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python3中打印括号内的两个变量?_Python_Variables_Printing_Var - Fatal编程技术网

如何在Python3中打印括号内的两个变量?

如何在Python3中打印括号内的两个变量?,python,variables,printing,var,Python,Variables,Printing,Var,我有一行代码: print ("(x %s)(x %s)") % (var_p1, var_p2) 但它不起作用,我是编程新手,我不知道我做错了什么。有没有专家能给出一个简单的答案 我想让它随机选择一个抛物线方程。e、 g.(x-3)(x+1)但是,它会出现错误消息: Traceback (most recent call last): "File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module> pr

我有一行代码:

print ("(x %s)(x %s)") % (var_p1, var_p2)
但它不起作用,我是编程新手,我不知道我做错了什么。有没有专家能给出一个简单的答案

我想让它随机选择一个抛物线方程。e、 g.(x-3)(x+1)但是,它会出现错误消息:

Traceback (most recent call last): 
"File "E:/Python34/MyFiles/Math Study Buddy.py", line 26 in <module> 
print ("(x %s)(x %s)") % (var_p1, var_p2) 
TypeError: unsupported operand type (s) for %: 'NoneType' and 'tuple'
回溯(最近一次呼叫最后一次):
“文件”E:/Python34/MyFiles/Math Study Buddy.py”,中的第26行
打印(“(x%s)(x%s)”)%(变量p1,变量p2)
TypeError:不支持%的操作数类型:“非类型”和“元组”

在python 3中,需要将变量放在字符串后面的括号内:

>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
请注意,在Python3中,print是一个函数,您需要传递字符串作为其参数。因此,您不能将变量放在函数之外

欲了解更多详情,请阅读

注意

这里描述的格式化操作表现出各种各样的怪癖,这些怪癖会导致许多常见错误(例如无法正确显示元组和字典)。使用较新的界面有助于避免这些错误,并且还提供了一种更强大、更灵活和可扩展的文本格式化方法


这里不需要使用“x”来替换变量。 这将解决以下问题:

print ("(%s)(%s)") % (var_p1, var_p2)
另外,.format优于%

见: 您可以使用


如前所述,在Python3中,您需要围绕要打印的整个内容使用aparenthesis。我在这里使用python2.7,因此您可能需要做一些更改。使用str.format
print(((x{})(x{})”)。format(var_p1,var_p2))
Thankyou@Padriac Cunningham,它成功了!
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2))) 
(x test)(x test2)