Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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

>>> print(f'''{var1}-{var2.replace("'","")}''')
foo-bar 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading