如何在 Python 中打印一串没有空格的变量(最少编码!) [英] How to print a string of variables without spaces in Python (minimal coding!)

查看:54
本文介绍了如何在 Python 中打印一串没有空格的变量(最少编码!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的东西:print "\n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"

它为每个变量打印空格.

It prints with spaces for each variable.

| 1 | john | h | johnny | mba |

我想要这样的东西:

|1|john|h|johnny|mba|

我有 20 个变量需要打印,我讨厌对每个变量都使用 sys.stdout.write(var).感谢 Pythonistas!

I have 20 variables that I have to print and I hate use sys.stdout.write(var) for each one of them. Thanks Pythonistas!

推荐答案

尝试使用join:

print "\n"+'|'.join([id,var1,var2,var3,var4])

或者如果变量还不是字符串:

or if the variables aren't already strings:

print "\n"+'|'.join(map(str,[id,var1,var2,var3,var4]))

这种方法的好处是您不必构建长格式字符串,而且对于任意数量的变量,它基本上可以保持不变.

The benefit of this approach is that you don't have to build a long format string and it basically works unchanged for an arbitrary number of variables.

这篇关于如何在 Python 中打印一串没有空格的变量(最少编码!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆