组合 f 字符串和原始字符串文字

我想知道如何在使用 r获取原始字符串文字的同时使用 f 字符串。我目前有它如下,但希望选择允许任何名称取代 Alex我想添加一个 f 字符串,然后取代 Alex与花括号,并把用户名放在里面,但这不适用于 r

username = input('Enter name')
download_folder = r'C:\Users\Alex\Downloads'
45125 次浏览

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.

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...

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.

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)

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}"


print(half_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}"


print(full_escaped)
# escaped_too_\n_escaped

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-2022\n'
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\’
f‘{user}’
r‘\Downloads’)
print(dir_out) #C:\Users\Alex\Downloads

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