故障コード:の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)
新しい問題:
1つの余分な空白があります(私はそれをマークした_)整数値の前に、MIN_WIDTH桁intigers用:マッピングキーを追加する方法があるかどう
print raw_str
... from _10234 to _12890 ...
はまた、私は疑問に思いますか?はるかに使用可能なよりも私には思われる(代わりの13以上の
a = ["123", "12"]
max_width = sorted([len(i) for i in a])[-1]
プットMAX_WIDTHと、単一のアレイ内のすべての文字列を置く:
imho、2番目の数字をパディングする必要はありません - それはすでに最小幅を持っています –
真、2つの数字pos_1が負であり、したがって否定のために余分な文字が必要な場合には必要かもしれません)両方の幅を渡す方が安全です。 – Amber
ありがとう、これまでのところ!塗りつぶし文字を* 0 *から*空白*に変更した後、ちょっとした問題にぶつかります。あなたが私の新しい例を見ることができれば嬉しいです。 – SimonSalman