如何在 Python 3 中打印括号内的两个变量?
How do you print two variables within brackets in Python 3?
我有这行代码:
print ("(x %s)(x %s)") % (var_p1, var_p2)
但这不起作用,我是编程新手,我不知道自己做错了什么。有专家给出简单的答案吗?
我想让它随机 select 一个抛物线方程。例如(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'
正如您在 python 3 中一样,您需要将变量放在字符串后的括号内:
>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
注意 python 3 print
是一个函数,你需要传递字符串作为它的 argument.So 你不能放你在函数外的变量!
有关详细信息,请阅读 printf-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
您不需要使用 'x' 在这里替换变量。
这将修复:
print ("(%s)(%s)") % (var_p1, var_p2)
此外,.format 优于 %
见:
Python string formatting: % vs. .format
您可以使用 str.format
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2)))
(x test)(x test2)
我有这行代码:
print ("(x %s)(x %s)") % (var_p1, var_p2)
但这不起作用,我是编程新手,我不知道自己做错了什么。有专家给出简单的答案吗?
我想让它随机 select 一个抛物线方程。例如(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'
正如您在 python 3 中一样,您需要将变量放在字符串后的括号内:
>>> print ("(x %s)(x %s)"%(2, 3))
(x 2)(x 3)
注意 python 3 print
是一个函数,你需要传递字符串作为它的 argument.So 你不能放你在函数外的变量!
有关详细信息,请阅读 printf-style String Formatting
Note
The formatting operations described here exhibit a variety of quirks that lead to a number of common errors (such as failing to display tuples and dictionaries correctly). Using the newer str.format() interface helps avoid these errors, and also provides a generally more powerful, flexible and extensible approach to formatting text.
您不需要使用 'x' 在这里替换变量。 这将修复:
print ("(%s)(%s)") % (var_p1, var_p2)
此外,.format 优于 %
见: Python string formatting: % vs. .format
您可以使用 str.format
>>> var_p1 = 'test'
>>> var_p2 = 'test2'
>>> print(("(x {})(x {})".format(var_p1, var_p2)))
(x test)(x test2)