开发者

Is there a more agile way to re-factor the following string formating code

I need to format a string as bellow :

print "%8s%-32s%-32s%-32s" % (' ', 'CAT A', 'CAT B', 'CAT C')

Since the number of cat is a variable, here is what I code.

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开发者_Go百科']
${format % tuple(values)}

The code doesn't seem short and agile. Is there any other way to code it in python style?


How about:

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)

Note the use of * to indicate a variable width specifier, and the %c format specifier for a single character to avoid using chr().


Why not:

" "*8 + "%-32s"*len(values) % tuple(values)

then:

values=["CAT "+chr(65+i) for i in house.get_cat_count()]
" "*8 + ("%%-%ds" % house.get_width()) * len(values) % tuple(values)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜