简体   繁体   English

串联字符串的字符串格式?

[英]String formatting on concatenated strings?

I run into this situation: 我遇到这种情况:

msg = 'stackoverflow is {subject}'+ ' for me'.format(subject='useful')

msg = 'stackoverflow is {subject}'.format(subject='useful') + ' for me'

First one prints: 第一张照片:

stackoverflow is {subject} for me stackoverflow对我来说是{subject}

Second one prints: 第二张照片:

stackoverflow is useful for me stackoverflow对我有用

Does not concatenating two strings make a new string that should be treated as a normal string for string formatting input? 不能将两个字符串连接在一起就构成一个新字符串,对于字符串格式输入,该新字符串应视为普通字符串?

Yes, but you would need to use parenthesis in the first solution: 是的,但是您需要在第一个解决方案中使用括号:

msg = ('stackoverflow is {subject}' + ' for me').format(subject='useful')

Otherwise, the .format call will only apply to the ' for me' string, which is effectively a no-op: 否则, .format调用将仅适用于' for me'字符串,实际上是一个空操作:

>>> ' for me'.format(subject='useful')
' for me'
>>>

With the parenthesis however, the 'stackoverflow is {subject}' and ' for me' string literals will first be combined: 但是,使用括号将'stackoverflow is {subject}'' for me'字符串文字首先进行组合:

>>> ('stackoverflow is {subject}' + ' for me')
'stackoverflow is {subject} for me'
>>>

and then .format will be called on the resulting string. 然后将在结果字符串上调用.format


Also, just for the record, you do not need to use + in this case since adjacent string literals are automatically concatenated in Python: 同样,仅出于记录目的,在这种情况下,您不需要使用+ ,因为相邻的字符串文字在Python中会自动连接在一起:

>>> 'a''b'
'ab'
>>> 'a'      'b'
'ab'
>>>

In the above example you're calling .format() on the last string, for me and therefore not the formatting doesn't work as you expected it to. 在上面的示例中, for me ,您在最后一个字符串上调用.format() ,因此格式化不符合您的预期。

Wrap your string concat in parenthesis and call format on the resulting string and the formatting will work. 将您的字符串concat用括号括起来,然后对结果字符串调用格式,格式将起作用。

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

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