Skip to main content
 首页 » 编程设计

python之使用变量在python中指定格式

2025年05月04日9luoye11

我想将一个字符串格式化为固定宽度

如果我使用下面的语句:

"{0:<8}".format(str(size)) #This one works 

但是,

# This one gives Invalid conversion specification 
"{0:<width}".format(str(size))  

有没有办法使用变量来格式化字符串?

请您参考如下方法:

解决方案一:
使用 width生成字符串 {0:<8}第一

width = 8 
("{0:<%d}"%width).format(s) 

方案二:
嵌套 format :

"{0:<{1}}".format(s, width) 

命名格式可能更具可读性:

"{string:<{width}}".format(string=s, width=width) 

方案三:
另一种翻译方式 {0:<8} : .ljust(8)

"{0}".format(s.ljust(width)) 

我选择3.当
1) 处理i18n中的其他编码
2)打印漂亮

print 'a'.rjust(10, '-') 
---------a