Combine f-string and raw string literal

隐身守侯 提交于 2020-06-25 09:47:08

问题


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'

回答1:


You can combine the f for an f-string with the r for a literal.

user = 'Alex'
dirToSee = fr'C:\Users\{user}\Downloads'
print (dirToSee) # prints C:\Users\Alex\Downloads



回答2:


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.




回答3:


Raw f-strings are very useful when dealing with dynamic regular expressions. https://www.python.org/dev/peps/pep-0498/ contains a lot of useful information.



来源:https://stackoverflow.com/questions/58302531/combine-f-string-and-raw-string-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!