Python 有没有更灵活的方法来重新考虑以下字符串格式化代码
我需要将字符串格式化为以下格式:Python 有没有更灵活的方法来重新考虑以下字符串格式化代码,python,Python,我需要将字符串格式化为以下格式: print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C') 因为cat的数量是一个变量,下面是我的代码 values = [' ', ] format = "%8s" # width is a variable width = house.get_width() for cat in range(house.get_cat_count()): format = format + '%-'
print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')
因为cat的数量是一个变量,下面是我的代码
values = [' ', ]
format = "%8s"
# width is a variable
width = house.get_width()
for cat in range(house.get_cat_count()):
format = format + '%-' + str(width) + 's'
values.append('CAT ' + chr(ord('A') + operator))
# format is "%8s%-32s%-32s%-32s"
# values is [' ', 'CAT A', 'CAT B', 'CAT C']
${format % tuple(values)}
这段代码看起来并不简短和灵活。有没有其他方法可以用python风格对其进行编码?为什么没有:
" "*8 + "%-32s"*len(values) % tuple(values)
然后:
那么:
result = ' ' * 8
width = house.get_width() - 4 # subtract 4 to allow for 'CAT '
for i in range(house.get_cat_count()): # or xrange
result += 'CAT %-*c' % (width, ord('A') + i)
注意使用*
表示可变宽度说明符,使用%c
格式说明符表示单个字符,以避免使用chr()
result = ' ' * 8
width = house.get_width() - 4 # subtract 4 to allow for 'CAT '
for i in range(house.get_cat_count()): # or xrange
result += 'CAT %-*c' % (width, ord('A') + i)