4

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?

1 Answer 1

3

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

>>> print(f'''{var1}-{var2.replace("'","")}''')
foo-bar 
Sign up to request clarification or add additional context in comments.

5 Comments

oh wow, that's both the easiest and fastest solution I've ever gotten. Thank you so much!
Bonus: Triple quoted strings can span multiple lines and keep the newline character in the string.
You can nest one layer further, since you have access to both single and double triple quoted strings. That being said, this is probably a moment when you should step back and ask yourself if you ever plan on being able to read this code in the future.
@Matthias that I knew and already use, but just couldn't wrap my head around it why I need 3 quotes for such a replace (and still can't but hey it works :))
@JVGBI. Because you can't escape things in an f-string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.