1

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?

wjandrea
  • 23,210
  • 7
  • 49
  • 68
NorthWind4721
  • 61
  • 1
  • 5
  • 2
    `print(mystring.replace("\\", "\\\\"))` - compare with `print(mystring)` – alani Jul 16 '20 at 00:06
  • That's a backslash \. A slash leans the other way /. – wjandrea Jul 16 '20 at 01:18
  • Does this answer your question? [python replace single backslash with double backslash](https://stackoverflow.com/questions/17327202/python-replace-single-backslash-with-double-backslash) – wjandrea Jul 16 '20 at 01:35
  • Also related: [How to double a char in a string?](https://stackoverflow.com/q/22605967/4518341), [Replace part of a string in Python?](https://stackoverflow.com/q/10037742/4518341), maybe [Why do backslashes appear twice?](https://stackoverflow.com/q/24085680/4518341) and [Windows path in Python](https://stackoverflow.com/q/2953834/4518341) – wjandrea Jul 16 '20 at 01:35

4 Answers4

2

Did you try the str.replace?

>>> s = 'C:\\Users'
>>> s = s.replace('\\', '\\\\')
>>> s
'C:\\\\Users'
>>> print(s)
C:\\Users
Damião Martins
  • 914
  • 5
  • 15
  • I edited the code already, but just wanted to mention, don't use `input` as a variable name since it shadows the builtin `input()`. – wjandrea Jul 16 '20 at 01:25
2

You do not need any special handling:

 a = 'abc\def'
 print(repr(a))
 #'abc\\def'
 print(a)
 #'abc\def'
Danizavtz
  • 2,845
  • 4
  • 25
  • 22
  • Note that `'\d'` will be invalid in a future version of Python. You should write `'\\d'` instead. See [docs](https://docs.python.org/3/reference/lexical_analysis.html#index-23). – wjandrea Jul 16 '20 at 01:22
2

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
Ann Zen
  • 25,080
  • 7
  • 31
  • 51
0

Would definitely go with the .replace() method:

object.replace("\\", "\\\\")
Ann Zen
  • 25,080
  • 7
  • 31
  • 51
Michele Giglioni
  • 319
  • 3
  • 15
  • The syntax is wrong. You need to double the backslashes. Anyway this method was [already posted](https://stackoverflow.com/a/62925525/4518341). – wjandrea Jul 16 '20 at 01:23