Reputation: 5237
Given some variable
flag = True
x = "hello"
y = "world"
I would like to print the following string:
"hello world"
if flag is True
or "hello 'world'"
if flag is False
.
This could be done using the following statement:
print("{} {}".format(x, y if flag else "'{}'".format(y)))
The question is, can such a conditional format be specified directly using pyformat? I.e. is it possible to specify different format strings depending on some variable?
One solution might be to do two formats:
'{{}} {}'.format("{}" if flag else "'{}'").format(x, y)
But this makes it very hard to read as you have to escape the not replaced formats in the first string.
Upvotes: 2
Views: 294
Reputation: 1142
Although I like @schwobaseggl's solution alot, I feel that you're better of just doing a proper if
:
if flag:
print(f"{x} {y}")
else:
print(f"{x} '{y}')
This will make your code much more readable and maintainable. Otherwise it feel's like you're just trying to hide away the if and making spaghetti.
Upvotes: 1
Reputation: 5795
Try this,
>>> print("{x} {flag}{y}{flag}".format(x=x,y=y, flag= "" if flag else "'"))
hello world
>>> flag = False
>>> print("{x} {flag}{y}{flag}".format(x=x,y=y, flag= "" if flag else "'"))
hello 'world'
Upvotes: 0
Reputation: 73498
I do not think it is possible to select different format strings like that. In your concrete case, you could be more concise with some trickery:
("{} '{}'", "{} {}")[flag].format(x, y)
# 'hello world'
flag = False
("{} '{}'", "{} {}")[flag].format(x, y)
# "hello 'world'"
In general, a dict
mapping of possible values of the controlling variable to their corresponding format strings would be simple enough.
Upvotes: 0
Reputation: 4358
If you have python 3.6 or greater, you can use f'strings: print(f"{x} {y}" if flag else f"{x} '{y}'")
.
More info: https://www.python.org/dev/peps/pep-0498/
Upvotes: 0