Python f-string with raw strings It is used when we want the escape sequences i.e. '\n' or backslash(\) as literal sequences of characters. Python f-strings can work well simultaneously with the raw strings. In the above example, '\n' is treated as a literal character.
String Concatenation using f-stringIf you are using Python 3.6+, you can use f-string for string concatenation too. It's a new way to format strings and introduced in PEP 498 - Literal String Interpolation.
tl;dr: You can compose verbose regular expressions using f-strings. For comparison, the same pattern without f-strings (click to expand).
You can combine the f
for an f-string with the r
for a raw string:
user = 'Alex'
dirToSee = fr'C:\Users\{user}\Downloads'
print (dirToSee) # prints C:\Users\Alex\Downloads
The r
only disables backslash escape sequence processing, not f-string processing.
Quoting the docs:
The 'f' may be combined with 'r', but not with 'b' or 'u', therefore raw formatted strings are possible, but formatted bytes literals are not.
...
Unless an 'r' or 'R' prefix is present, escape sequences in string and bytes literals are interpreted...
Alternatively, you could use the str.format()
method.
name = input("What is your name? ")
print(r"C:\Users\{name}\Downloads".format(name=name))
This will format the raw string by inserting the name
value.
Raw f-strings are very useful when dealing with dynamic regular expressions. https://www.python.org/dev/peps/pep-0498/#raw-f-strings contains a lot of useful information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With