NorthWind4721
NorthWind4721

Reputation: 85

Is there a way to insert an extra "\" into a string in Python?

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

Answers (4)

Damião Martins
Damião Martins

Reputation: 1849

Did you try the str.replace?

>>> s = 'C:\\Users'
>>> s = s.replace('\\', '\\\\')
>>> s
'C:\\\\Users'
>>> print(s)
C:\\Users

Upvotes: 2

Michele Giglioni
Michele Giglioni

Reputation: 339

Would definitely go with the .replace() method:

object.replace("\\", "\\\\")

Upvotes: 0

Red
Red

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

Danizavtz
Danizavtz

Reputation: 3270

You do not need any special handling:

 a = 'abc\def'
 print(repr(a))
 #'abc\\def'
 print(a)
 #'abc\def'

Upvotes: 2

Related Questions