Search code examples
pythonstringtextnlpf-string

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:

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'