简体   繁体   English

python字符串格式化操作

[英]python String Formatting Operations

Faulty code: 错误代码:

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}

Required output: 要求的输出:

... from 00234 to 12890 ...

           ______________________EDIT______________________

New code: 新代码:

# 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)

New Problem: 新问题:

There is one extra whitespace (I marked it _ ) in front of the integer values, for intigers with min_width digits: 整数值前面有一个额外的空格(我将其标记为_ ),用于带有min_width数字的Intiger

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

Also, I wonder if there is a way to add Mapping keys? 另外,我想知道是否有添加映射键的方法吗?

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")

Should do what you need 应该做你需要的

addition: 加成:

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

put max_width instead of 13 above and put all your strings in a single array a (which seems to me much more usable than having a stack of variables). 将max_width而不是上面的13放进去,并将所有字符串放在单个数组a中(在我看来,这比使用一堆变量要有用得多)。

additional nastyness: (Using array of numbers to get closer to your question.) 额外的麻烦:(使用数字数组更贴近您的问题。)

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

Who said Perl is the only language to easily produce braindumps in? 谁说Perl是唯一容易引起脑筋急转弯的语言? If regexps are the godfather of complex code, then list comprehension is the godmother. 如果正则表达式是复杂代码的教父,则列表理解是教母。

(I am relatively new to python and rather convinced that there must be a max-function on arrays somewhere, which would reduce above complexity. .... OK, checked, there is. Pity, have to reduce the example.) (我对python来说还比较陌生,而是深信在某个地方的数组上必须有一个max-function,这将降低上述复杂性。...好吧,检查一下,有。可惜,必须减少示例。)

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

And please observe below comments on "not putting calculation of an invariant (the max value) inside the outer list comprehension". 并且请注意以下有关“不将计算不变式(最大值)放入外部列表推导中”的注释。

Concerning using a mapping type as second argument to '%': 关于将映射类型用作'%'的第二个参数:

I presume you mean something like that '%(mykey)d' % {'mykey': 3} , right?! 我想您是说类似'%(mykey)d'%{'mykey':3}的意思 ,对吧? I think you cannot use this if you use the "%*d" syntax, since there is no way to provide the necessary width arguments with a dict. 我认为如果使用“%* d”语法,则无法使用此方法,因为无法为字典提供必要的宽度参数。

But why don't you generate your format string dynamically: 但是为什么不动态生成格式字符串:

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

This way you decouple the width issue from the formatting of the actual values, and you can use a tuple or a dict for the latter, as it suits you. 这样,您就可以将宽度问题与实际值的格式分离开来,并且可以为后者使用元组或dict,因为它适合您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM