Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 有没有更灵活的方法来重新考虑以下字符串格式化代码_Python - Fatal编程技术网

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)