【发布时间】:2009-08-05 08:04:10
【问题描述】:
错误代码:
pos_1 = 234
pos_n = 12890
min_width = len(str(pos_n)) # is there a better way for this?
# How can I use min_width as the minimal width of the two conversion specifiers?
# I don't understand the Python documentation on this :(
raw_str = '... from %(pos1)0*d to %(posn)0*d ...' % {'pos1':pos_1, 'posn': pos_n}
需要的输出:
... from 00234 to 12890 ...
______________________EDIT______________________
新代码:
# I changed my code according the second answer
pos_1 = 10234 # can be any value between 1 and pos_n
pos_n = 12890
min_width = len(str(pos_n))
raw_str = '... from % *d to % *d ...' % (min_width, pos_1, min_width, pos_n)
新问题:
整数值前面有一个额外的空格(我将其标记为 _),用于具有 min_width 位的整数:
print raw_str
... from _10234 to _12890 ...
另外,我想知道是否有办法添加映射键?
【问题讨论】:
标签: python string formatting