繁体   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