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

Combining Python f-string and r-string not behaving as expected

I have a variable that contains a string, that I’d like to print literally, so the newline is escaped. Printing the variable does not escape the newline:

bad_string = 'http://twitter.com/blo\r\n+omberg'
print(bad_string)
>>> http://twitter.com/blo
+omberg

Printing the value using an r-string results in what I’d want:

print(r'http://twitter.com/blo\r\n+omberg')
>>> http://twitter.com/blo\r\n+omberg

However, using an f-string with the variable, and combining it with an r-string, does not:

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

print(rf'{bad_string}')
>>> http://twitter.com/blo
+omberg

I’m confused why this happens. I’d expect the combination of r and f string to print it literally. How can I print the literal value of a string variable with an f-string?

I’m using Python 3.6.13

>Solution :

Raw strings only concern themselves with the static literal part, so your rf'{bad_string}' is the same as bad_string.

Depending on what this is for, the repr builtin may be what you need

In [71]: print(repr("string\nwith\nnewline"))
'string\nwith\nnewline'

Or you can simply replace the newlines using the replace method.

There’s also the unicode_escape "encoding", but this’ll also replace any non ascii value:

In [77]: "\n".encode("unicode_escape").decode()
Out[77]: '\\n'

In [78]: "仮".encode("unicode_escape").decode()
Out[78]: '\\u4eee'
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