pe9*_*298 4 python printing format newline python-3.x
我正在使用 Python 3 并尝试将我的打印语句与 str.format 一起使用。
例如:
print ('{0:3d} {1:6d} {2:10s} '.format (count1,count2,string1))
Run Code Online (Sandbox Code Playgroud)
当我尝试使用 end=''
来抑制后续的换行符时,这被忽略了。换行总是发生。
如何抑制后续的换行符?
来源:
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.
Run Code Online (Sandbox Code Playgroud)
1 999 qwerty
换行符1 999 qwerty
换行符
您的问题是您将end=''
参数传递给format
函数,而不是传递给print
函数。
改变这一行:
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1,end=''))
Run Code Online (Sandbox Code Playgroud)
对此:
print ( '{0:3d} {1:6d} {2:10s} '.format (int1,int2,string1), end='')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您还应该阅读PEP8。它定义了 Python 编码风格的标准,你真的应该尝试遵循这些标准,除非你和一群同意其他风格标准的人一起工作。特别是,函数调用周围的间距有点奇怪 - 函数名称和参数括号之间或括号和第一个参数之间不应该有空格。我以一种保持您当前风格的方式为您的问题编写了建议的解决方案,但它实际上应该看起来更像这样:
print('{0:3d} {1:6d} {2:10s} '.format(int1, int2, string1), end='')
Run Code Online (Sandbox Code Playgroud)