The output is "Hello. I'm Santiago", but I would like to print "Hello. I'm Santiago and i love Python
". I have never used conditions on the same line. I'm new to Python.
The 2 2 condition is just a simple example. I wish if the condition is true then I get the output "Hello. I'm Michael and i love Python"? I need "\"
to write in each different staff as I did.
I don't want to use the solution f"{b}" f"{c}" if 2 2 == 4 else ""
, but keep the code structure as in the question
How can I solve?
a = "Hello. "
b = "I'm Santy"
c = " and i love Python"
x = f"{a}" \
f"{b}" if 2 2 == 4 else "" \
f"{c}"
print(x)
CodePudding user response:
The problem is that the \
at the end of each line doesn't do what you think it does. The ""
is concatenated with the f"{c}"
before the if...else
is evaluated.
One way to solve this is to add litera
es to concatenate the strings. You also need to add parentheses to force the correct order of operations.
x = f"{a}" \
(f"{b}" if 2 2 == 4 else "") \
f"{c}"
But then you don't need f""
:
x = a \
(b if 2 2 == 4 else "") \
c
While this is fine for investigating python out of intellectual curiosity, I strongly recommend that you avoid trying to do everything in a single statement. Instead, break up your logic into discreet steps that concatenate strings together. Use if statements rather than if expressions for conditional parts of the string. In general, KISS it (Keep It Simple Stupid).
CodePudding user response:
Your problem is one of operator precedence. String concatenation (implied or explicit using
) has higher precedence than if-else
(see the manual) so your expression evaluates as:
x = (f"{a}" f"{b}") if 2 2==4 else ("" f"{c}")
which will yield either "Hello. I'm Santy"
or " and i love Python"
. To make c
dependent on the condition, you must parenthesise that condition and make it apply only to c
(note I've substituted True
for your condition for simplicity):
x = f"{a}" f"{b}" (f"{c}" if True else "")
Output:
"Hello. I'm Santy and i love Python"
Note that you need to use a
before the condition as a parenthesised expression is not a string literal which can be concatenated without an operator.
Then the False
condition:
x = f"{a}" f"{b}" (f"{c}" if False else "")
Output:
"Hello. I'm Santy"
Written as multi-line code:
x = f"{a}" \
f"{b}" \
(f"{c}" if False else "")
CodePudding user response:
The f"{c}"
and the f"{b}" if 2 2 == 4 else ""
are "joined up". You can fix this by changing it to:
f"{a}" \
f"{b}"f"{c}" if 2 2 == 4 else "" \
Or:
f"{a}" \
(f"{b}" if 2 2 == 4 else "") f"{c}"