Replace value of variable directly inside f-string

Question:

I’m trying to replace a value inside a variable that I use within an f-string. In this case it is a single quote. For example:

var1 = "foo"
var2 = "bar '"

print(f"{var1}-{var2}")

Now, I want to get rid of the single quote within var2, but do it directly in the print statement. I’ve tried:

print(f"{var1}-{var2.replace("'","")}")

which gives me: EOL while scanning string literal.

I do not want to impose a third variable, so no var3 = var2.replace(",","") etc…

I would rather not use a regex, but if there is no other way, please tell me how to do it.

What is the best way to solve this?

Asked By: JVGBI

||

Answers:

When the contents contains both ' and ", you can use a triple quoted string:

>>> print(f'''{var1}-{var2.replace("'","")}''')
foo-bar 
Answered By: wim
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.