禁止以python 3 str.format打印换行符 [英] Suppress print newline in python 3 str.format
问题描述
我正在使用Python 3,并尝试将我的打印语句与str.format一起使用.
I am using Python 3 and am trying to use my print statements with the str.format.
例如:
print ('{0:3d} {1:6d} {2:10s} '.format (count1,count2,string1))
当我尝试使用end=''
禁止显示后续换行符时,将忽略此内容.换行总是发生.
When I try to use the end=''
to suppress the subsequent newline, this is ignored. A newline always happens.
如何取消后续的换行符?
How do I suppress the subsequent newline?
来源:
int1= 1
int2 = 999
string1 = 'qwerty'
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1))
print ('newline')
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1,end=''))
print ('newline')
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
[GCC 4.8.2] on linux
Type "copyright", "credits" or "license()" for more information.
1 999 qwerty
换行符
1 999 qwerty
newline
1 999 qwerty
换行符
1 999 qwerty
newline
推荐答案
您的问题是您将end=''
参数传递给了format
函数,而不是传递给了print
函数.
Your problem is that you have the end=''
argument being passed to the format
function, not to the print
function.
更改此行:
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1,end=''))
对此:
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1), end='')
顺便说一句,您还应该阅读 PEP8 .它定义了Python编码样式的标准,除非您正在与一群已就其他样式标准达成协议的人员合作,否则您确实应该遵循这些标准.特别是,函数调用之间的间距有些奇怪-函数名称与参数括号之间或括号与第一个参数之间不应有空格.我以保持您当前风格的方式写出了针对您问题的建议解决方案,但实际上它看起来应该更像这样:
By the way, you should also give PEP8 a read. It defines standards for Python coding styles, that you really should try to follow, unless you're working with a group of people that have agreed on some other style standards. In particular, your spacing is a bit weird around function calls - you shouldn't have spaces between function names and the argument parentheses, or between the parentheses and the first argument. I wrote my suggested solution to your problem in a way that maintains your current style, but it really should look more like this:
print('{0:3d} {1:6d} {2:10s} '.format(int1, int2, string1), end='')
这篇关于禁止以python 3 str.format打印换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!