我想将字符串格式化为固定宽度
如果我使用以下声明:
"{0:<8}".format(str(size)) #This one works
Run Code Online (Sandbox Code Playgroud)
然而,
# This one gives Invalid conversion specification
"{0:<width}".format(str(size))
Run Code Online (Sandbox Code Playgroud)
无论如何使用变量来格式化字符串?
解决方法1:
使用width生成的字符串{0:<8}第一
width = 8
("{0:<%d}"%width).format(s)
Run Code Online (Sandbox Code Playgroud)
解决方案2:
嵌套format:
"{0:<{1}}".format(s, width)
Run Code Online (Sandbox Code Playgroud)
命名格式可能更具可读性:
"{string:<{width}}".format(string=s, width=width)
Run Code Online (Sandbox Code Playgroud)
解决方案3:
另一种翻译方式{0:<8}:.ljust(8)
"{0}".format(s.ljust(width))
Run Code Online (Sandbox Code Playgroud)
我选择3.当
1)处理其他编码的国际化
2)打印漂亮
print 'a'.rjust(10, '-')
---------a
Run Code Online (Sandbox Code Playgroud)