Reputation: 85
I am trying to turn the regular '\'
(single backslash) in a file path, which the user inputs in the form of a string, to two backslashes.
Is there a way to do this?
Upvotes: 1
Views: 169
Reputation: 1849
Did you try the str.replace
?
>>> s = 'C:\\Users'
>>> s = s.replace('\\', '\\\\')
>>> s
'C:\\\\Users'
>>> print(s)
C:\\Users
Upvotes: 2
Reputation: 339
Would definitely go with the .replace()
method:
object.replace("\\", "\\\\")
Upvotes: 0
Reputation: 27567
Here is how you can use an r
string:
path = input("Input the path: ")
print(path.replace('\\',r'\\'))
Input:
Input the path: C:\Users\User\Desktop
C:\\Users\\User\\Desktop
Upvotes: 2
Reputation: 3270
You do not need any special handling:
a = 'abc\def'
print(repr(a))
#'abc\\def'
print(a)
#'abc\def'
Upvotes: 2