故障代碼:Python字符串格式化操作
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)
新的問題:
有一個多餘的空格(我標記了_)的整數值的前面,爲intigers與MIN_WIDTH位數:
print raw_str
... from _10234 to _12890 ...
另外,我不知道是否有添加映射鍵的方法嗎?
imho,你不需要填寫第二個數字 - 它已經有最小寬度 – 2009-08-05 08:26:43