簡體   English   中英

python字符串格式化操作

[英]python String Formatting Operations

錯誤代碼:

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數字的Intiger

print raw_str
... from _10234 to _12890 ...

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

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)
"1234".rjust(13,"0")

應該做你需要的

加成:

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

將max_width而不是上面的13放進去,並將所有字符串放在單個數組a中(在我看來,這比使用一堆變量要有用得多)。

額外的麻煩:(使用數字數組更貼近您的問題。)

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-function,這將降低上述復雜性。...好吧,檢查一下,有。可惜,必須減少示例。)

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

並且請注意以下有關“不將計算不變式(最大值)放入外部列表推導中”的注釋。

關於將映射類型用作'%'的第二個參數:

我想您是說類似'%(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

這樣,您就可以將寬度問題與實際值的格式分離開來,並且可以為后者使用元組或dict,因為它適合您。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM