Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace value of variable directly inside f-string

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?

like image 370
JVGBI Avatar asked Sep 03 '25 17:09

JVGBI


1 Answers

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

>>> print(f'''{var1}-{var2.replace("'","")}''')
foo-bar 
like image 59
wim Avatar answered Sep 07 '25 04:09

wim