打印包含串联字符串的变量时出现多余字符的麻烦

时间:2019-01-23 05:58:53

标签: python

尝试打印包含串联字符串的变量时遇到问题,如下所示:

num1 = int(input("Choose a number: "))
num2 = int(input("Choose a second number: "))

total_int = num1 * num2
total_str = total_int, "is the answer"
print(total_str)

运行此命令(例如输入4和5)时得到的是(20, 'is the answer') 为什么还要打印括号,单引号和逗号? 我了解通过执行以下操作,我可以获得没有这些结果的结果

print(num1,'multiplied by',num2,'is',total_int)

但是我想尽可能打印出存储在变量中的内容。

2 个答案:

答案 0 :(得分:0)

您实际上是在创建一个元组,而不是连接字符串。您可以使用+运算符:

num1 = int(input("Choose a number: "))
num2 = int(input("Choose a second number: "))

total_int = num1 * num2
total_str = str(total_int) + " is the answer"
print(total_str)

但是,格式字符串是首选选项:

total_str = "{0} is the answer".format(total_int)

对于Python 3.6 +:

total_str = f"{total_int} is the answer"

如果您确实想保留将多个参数传递给print的行为,请尝试以下操作:

num1 = int(input("Choose a number: "))
num2 = int(input("Choose a second number: "))

total_int = num1 * num2
total_str = total_int, "is the answer"
print(*total_str) # <- notice the `*` operator

答案 1 :(得分:0)

num1 = int(input("Choose a number: "))
num2 = int(input("Choose a second number: "))

total_int = num1 * num2
print("{} is the answer".format(total_int)) 

{}将打印变量值.format()是您要打印的值