Skip to content
Advertisement

Combine f-string and raw string literal

I’m wondering how to use an f-string whilst using r to get a raw string literal. I currently have it as below but would like the option of allowing any name to replace Alex I was thinking adding an f-string and then replacing Alex with curly braces and putting username inside but this doesn’t work with the r.

username = input('Enter name')
download_folder = r'C:UsersAlexDownloads'

Advertisement

Answer

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:UsersAlexDownloads

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…

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement