2

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

Second one prints:

stackoverflow is useful for me

Does not concatenating two strings make a new string that should be treated as a normal string for string formatting input?

2 Answers 2

6

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:

>>> ' 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'
>>>

and then .format will be called on the resulting string.


Also, just for the record, you do not need to use + in this case since adjacent string literals are automatically concatenated in Python:

>>> 'a''b'
'ab'
>>> 'a'      'b'
'ab'
>>>
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yea because '.' is being evaluated earlier than plus!
0

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.

Wrap your string concat in parenthesis and call format on the resulting string and the formatting will work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.