Combine f-string and raw string literal
PythonPython 3.xF StringPython Problem Overview
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:\Users\Alex\Downloads'
Python Solutions
Solution 1 - Python
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...
Solution 2 - Python
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.
Solution 3 - Python
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.
Solution 4 - Python
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
)