【问题标题】:Why does this print statement print my variables on new line each?为什么这个 print 语句在每个新行上打印我的变量?
【发布时间】:2023-02-20 23:01:54
【问题描述】:

当我运行这条语句时,每个变量都打印在一个新行上。

print(last_name,",",first_name,",",town,",",state,",",age)

我的目标是在同一行上的前一个变量之后打印每个变量。在做了一些研究后,我发现 end="" 可以做到这一点。

但是,当我将它添加到打印语句的末尾时,它只会将最后两个变量组合成一行。我该如何解决这个问题?

【问题讨论】:

标签: python printing


【解决方案1】:

在 age 之后添加以下语法:

,结束=“”)

例如,请参见下面的链接。

https://www.tutorialspoint.com/print-single-and-multiple-variable-in-python

如果这不起作用,请重新发布带有结束语句的代码。 另一种选择是只测试前两个带有 end = “ “ 的变量以查看它是否运行,然后在它运行时添加另一个变量并再次测试以查看它是否有效。希望这可以帮助。

【讨论】:

  • 您的答案可以通过其他支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以在in the help center找到更多关于如何写出好的答案的信息。
【解决方案2】:

正如@Julien 所说,您的变量很可能在每个变量的末尾包含 。您可以删除该字符并以您想要的格式打印的方法如下:

这假定所有元素都是字符串。

# first taking all of the items in a list replace the 
 character with nothing then joining the list with a comma between each element
print(','.join([x.replace('
', '') for x in [last_name, first_name, town, state, age]])) 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-18
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    相关资源
    最近更新 更多