noo*_*nee 28 python whitespace python-2.x
我想知道在打印东西时如何删除额外的空格.
就像我这样做:
print 'Value is "', value, '"'
Run Code Online (Sandbox Code Playgroud)
输出将是:
Value is " 42 "
Run Code Online (Sandbox Code Playgroud)
但我想要:
Value is "42"
Run Code Online (Sandbox Code Playgroud)
有没有办法做到这一点?
Mar*_*ers 44
print ...,
如果您不想要空格,请不要使用.使用字符串连接或格式.
级联:
print 'Value is "' + str(value) + '"'
Run Code Online (Sandbox Code Playgroud)
格式:
print 'Value is "{}"'.format(value)
Run Code Online (Sandbox Code Playgroud)
后者更灵活,请参阅str.format()
方法文档和格式化字符串语法部分.
您还会遇到较旧的%
格式样式:
print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)
Run Code Online (Sandbox Code Playgroud)
但这并不像新str.format()
方法那样灵活.
小智 20
只是一个简单的答案,我发现很容易用作启动器:类似于使用end=''
避免新行,你可以使用sep=''
避免白色空间...对于这个问题,这将是这样的:
print('Value is "', value, '"', sep = '')
可以帮助将来的某个人.
这是逗号,提供了额外的空白。
一种方法是使用字符串%
方法:
print 'Value is "%d"' % (value)
Run Code Online (Sandbox Code Playgroud)
就像printf
在C中一样,允许您%
通过在字符串本身中使用格式说明符来合并并格式化项目。另一个示例,显示了多个值的使用:
print '%s is %3d.%d' % ('pi', 3, 14159)
Run Code Online (Sandbox Code Playgroud)
就其价值而言,Python 3允许您为单个print
调用指定分隔符和终止符,从而大大改善了这种情况:
>>> print(1,2,3,4,5)
1 2 3 4 5
>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<
>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
108848 次 |
最近记录: |