如何在Python中打印没有空格的变量字符串(最小编码!)[重复]

时间:2021-10-14 21:41:33

This question already has an answer here:

这个问题在这里已有答案:

I have something like : print "\n","|",id,"|",var1,"|",var2,"|",var3,"|",var4,"|"

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

It prints with spaces for each variable.

它为每个变量打印空格。

| 1 | john | h | johnny | mba |

I want something like this :

我想要这样的东西:

|1|john|h|johnny|mba|

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

我有20个变量,我必须打印,我讨厌为每个变量使用sys.stdout.write(var)。谢谢Pythonistas!

4 个解决方案

#1


6  

Try using join:

尝试使用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.

这种方法的好处是你不必构建一个长格式字符串,它基本上对任意数量的变量都没有改变。

#2


7  

For a variable number of values:

对于可变数量的值:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])

#3


5  

print "\n|%s|%s|%s|%s" % (id,var1,var2,var3,var4)

Take a look at String Formatting.

看看String Formatting。

Edit: The other answers with join are better. Join expects strings.

编辑:加入的其他答案更好。加入期望字符串。

#4


2  

If you are using Python 2.6 or newer, use the new standard for formating string, the str.format method:

如果您使用的是Python 2.6或更高版本,请使用新标准格式化字符串str.format方法:

print "\n{0}|{1}|{2}|".format(id,var1,var2)

link text

链接文字

#1


6  

Try using join:

尝试使用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.

这种方法的好处是你不必构建一个长格式字符串,它基本上对任意数量的变量都没有改变。

#2


7  

For a variable number of values:

对于可变数量的值:

print '|%s|' % '|'.join(str(x) for x in [id, var1, var2, var3, var4])

#3


5  

print "\n|%s|%s|%s|%s" % (id,var1,var2,var3,var4)

Take a look at String Formatting.

看看String Formatting。

Edit: The other answers with join are better. Join expects strings.

编辑:加入的其他答案更好。加入期望字符串。

#4


2  

If you are using Python 2.6 or newer, use the new standard for formating string, the str.format method:

如果您使用的是Python 2.6或更高版本,请使用新标准格式化字符串str.format方法:

print "\n{0}|{1}|{2}|".format(id,var1,var2)

link text

链接文字