Combine f-string and raw string literal

后端 未结 3 1015
悲哀的现实
悲哀的现实 2021-02-05 04:35

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 rep

相关标签:
3条回答
  • 2021-02-05 05:24

    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
    
    0 讨论(0)
  • 2021-02-05 05:26

    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.

    0 讨论(0)
  • 2021-02-05 05:33

    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.

    0 讨论(0)
提交回复
热议问题