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'
Asked By: lammyalex



Alternatively, you could use the str.format() method.

name = input("What is your name? ")

This will format the raw string by inserting the name value.

Answered By: clubby789

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…

Answered By: rajah9

Since you are working with file paths, I would avoid f-strings and rather use a library geared for path manipulation. For example pathlib would allow you to do:

from pathlib import Path
username = input('Enter name')
download_folder = Path('C:/Users', username, 'Downloads')

This approach also offers some other common file operations such as, such as is_dir open.

Alternatively you could also use os.path.join)

Answered By: Nameless One

As others have mentioned, it’s indeed possible to mix r and f.
Be careful, though, since the interpolated strings will not be raw by default:

not_escaped = "not_escaped"
half_escaped = rf"escaped_{not_escaped}"

### outputs:
# escaped_
# ot_escaped

You’d have to use r for the interpolated strings too:

escaped = r"n_escaped"
full_escaped = rf"escaped_too_{escaped}"

# escaped_too_n_escaped
Answered By: Eric Duminil

The simplest way I’ve found of doing this is to use implicit line continuation to split my strings up into component parts, i.e. separate out ‘r’ and ‘f’ strings inside parenthases. Here’s an example matplotlib title with ‘normal’, ‘formatted’, and ‘raw’ string literals (read more here):

plt.title('Blind Surveys 01-FEB-2022n'
         f'Recording{n}; Mean dose rate: {m.get_mean_doserate()*1000:.4f}'
         r' $mathrm{mu}$Sv/hr', fontsize='x-large')

enter image description here

Just to make it more applicable to the question, you can also use implicit line continuation in variable declaration:

user = ‘Alex’
dir_out = (r‘C:Users’
print(dir_out) #C:UsersAlexDownloads

Admittedly this seems a bit overkill for this simple scenario but will be your friend when strings become more complex!

Answered By: compuphys

you can try:

username = input('Enter name')
download_folder = r'C:UsersAlexDownloads'
download_folder = download_folder.replace("Alex", username)
Answered By: Xuyang Zhu
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.