2009-08-05 184 views
0

故障代碼: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 ... 

另外,我不知道是否有添加映射鍵的方法嗎?

回答

2
pos_1 = 234 
pos_n = 12890 
min_width = len(str(pos_n)) 

raw_str = '... from %0*d to %0*d ...' % (min_width, pos_1, min_width, pos_n) 
+0

imho,你不需要填寫第二個數字 - 它已經有最小寬度 – 2009-08-05 08:26:43

1
"1234".rjust(13,"0") 

應該做你需要什麼

另外:

a = ["123", "12"]  
max_width = sorted([len(i) for i in a])[-1] 

放MAX_WIDTH而不是13的上方,並把所有的字符串在一個單一陣列中(這遠遠超過可在我看來,有一堆變量)。

額外nastyness:(數字用數組來接近你的問題)

a = [123, 33, 0 ,223] 
[str(x).rjust(sorted([len(str(i)) for i in a])[-1],"0") for x in a] 

誰說Perl是很容易產生的考題唯一的語言?如果正則表達式是複雜代碼的教父,那麼列表理解就是教母。我相對比較新的python,而且相信在數組的某個地方必須有一個max函數,這會降低以上的複雜性....好的,檢查,有。可惜,必須減少這個例子)

[str(x).rjust(max([len(str(i) for i in a]),"0") for x in a] 

請注意下面的註釋:「不把外加列表理解中的不變量(最大值)的計算」。

+0

謝謝,我打算用你對陣列的建議。 關於* rjust *:目前,我需要理解字符串格式化的*%*運算符,這就是爲什麼我會綁定它。對不起,應該提到這一點。 – SimonSalman 2009-08-05 09:33:51

+0

在執行.rjust()列表之前,您真的想要打破max()計算並將其捕獲到一個變量中。否則,您將重新計算外部列表中**每個**項的內部列表和max()值! (但是你對列表解析的一般評論很好:) – ThomasH 2009-08-05 12:09:21

1

使用映射類型作爲第二個參數,以 '%' 關於:

我想你的意思是類似的東西'%(的myKey)d' %{ '的myKey':3},右?!如果你使用「%* d」語法,我認爲你不能使用它,因爲沒有辦法提供必要的寬度參數和字典。

但是你爲什麼不動態生成的格式字符串:

fmt = '... from %%%dd to %%%dd ...' % (min_width, min_width) 
# assuming min_width is e.g. 7 fmt would be: '... from %7d to %7d ...' 
raw_string = fmt % pos_values_as_tuple_or_dict 

這樣,你從分離的實際值的格式寬度的問題,你可以使用一個元組或字典後者,因爲它適合你。