0

It seems as if string formatting doesn't work on concatenated strings. With concatenation the place holder gets printed literally:

>>> print("{}" + " OK".format("Text"))
{} OK

However, without concatenation the format gets printed as it should:

>>> print("{} OK".format("Text"))
Text OK

The same problem occurs with old-style %-formatting.

If I have a long multi-line string where I would like to concatenate a string that should be formatted, what is the recommended way?

2 Answers 2

2

You were attempting to perform the "format" operation prior to doing the concatenation. You can fix the precedence of operations by using parentheses:

>>> the_string = ("{}" + " OK").format("Text")
>>> print(the_string)
Text OK
Sign up to request clarification or add additional context in comments.

2 Comments

PEP8 seems to imply that this spacing is incorrect or frowned upon: python.org/dev/peps/pep-0008/…
The spacing does not break the code, so it is not "incorrect". It makes the code easier to read, so I added it for didactic reasons. If it helps ease your mind, I'll unpack the code a bit further.
1

You just need to fix the parenthesis:

print(("{}" + " OK").format("Text"))

6 Comments

Oh! I thought the format function was a method of the string. I would have thought that syntax would make the string into a single element tuple with a string in it! Anyway, tried it, it works!
This doesn't work (update: in Python 3) — print returns None.
Worked for me. In the python interpreter: >>> print("{}" + " OK").format("Text") Text OK
@00prometheus Are you sure it's not Boa's answer that worked? Oh, wait, sorry, you're using Python 2... Boa's answer will work in Python 2.7 and 3.x, so I think it's a better answer. In Python 2, I'd put a space after the print.
We are editing across each other :-) OK, yes, I am in python 2.7 at the moment, but I agree, a python3 compatible answer is preferable.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.