如果我想使格式化后的字符串动态可调,则可以从
print '%20s : %20s' % ("Python", "Very Good")
至
width = 20 print ('%' + str(width) + 's : %' + str(width) + 's') % ("Python", "Very Good")
但是,这里的字符串连接似乎很麻烦。还有其他简化方法吗?
您可以从参数列表中获取填充值:
print '%*s : %*s' % (20, "Python", 20, "Very Good")
您甚至可以动态插入填充值:
width = 20 args = ("Python", "Very Good") padded_args = zip([width] * len(args), args) # Flatten the padded argument list. print "%*s : %*s" % tuple([item for list in padded_args for item in list])