Skip to content
Advertisement

Am I able to use “f” to format string and “r” to find files at the same time?

I have this code where I am trying to prompt the user to input a path for a file and depending on the title of the file, it would rename it accordingly. This is what I have so far:

import os

path = input('PATH: ')
if 'Factssheet' in path:
    os.rename(path, #updated_name)

I want to rename the file to Fact Sheet if Factssheet appears inside the previous title. However, I have 2 issues at the moment. I know that you have to add “r” before specifying a path and I’m not sure why but it’s alright I guess. And I think I have to string format it in order to actually rename it? I honestly tried rf"{path}" but that does not work. I’ve also tried r"%s" % path but that’s also a no go for me.

Am I too far off track? Anything would be appreciated.

Advertisement

Answer

It is possible to use rf"...your string.." as follows

>>> path = "/this/is/a/path/"
>>> rf"{path}"
'/this/is/a/path/'

It is not necessary to use a raw or formatted string, you can write path directly.

Raw strings are useful when you need to escape characters, for example when you have a path, it will have multiple backslashes. In order to escape a backslash you have to use a double backslash '\', but with r you can write r'' directly.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement