Python Replace \\ with \

Python Replace \\ with \

There's no need to use replace for this.

What you have is a encoded string (using the string_escape encoding) and you want to decode it:

>>> s = r"Escaped\nNewline"
>>> print s
Escaped\nNewline
>>> s.decode('string_escape')
'Escaped\nNewline'
>>> print s.decode('string_escape')
Escaped
Newline
>>> "a\\nb".decode('string_escape')
'a\nb'

In Python 3:

>>> import codecs
>>> codecs.decode('\\n\\x21', 'unicode_escape')
'\n!'

Replace \\ with \ in Python 3.x

In case you're in a python shell and just evaluated the dir, it's sufficient to print(dir).

Otherwise you'd want to do print(dir.replace('\\\\', '\\')), which seems to be a very strange output from os.getcwd()

Keep in mind that '\' is an escape character and thus needs to be escaped itself.

Here's an example from Python shell:

>>> a = 'c:\\foo\\bar'
>>> a
'c:\\foo\\bar'
>>> print(a)
c:\foo\bar

Replace in python the \ of a Windows path with /

At the end, I've used the solution of DeepSpace for another part of my code and instead used the solution of ShadowRanger.
The code that I use now is:

raw_path=(str(input("please write down the exact path")))+"/"
raw_path.replace("\\","/")

Python replace / with \

You missed something: it is shown as \\ by the Python interpreter, but your result is correct: '\\'is just how Python represents the character \ in a normal string. That's strictly equivalent to \ in a raw string, e.g. 'some\\path is same as r'some\path'.

And also: Python on windows knows very well how to use / in paths.

You can use the following trick though, if you want your dislpay to be OS-dependant:

In [0]: os.path.abspath('c:/some/path')
Out[0]: 'c:\\some\\path'

Python replace '\' with '/' where '\' is followed by 't'

\t , \f, \n, etc. are escape sequences. So, whenever you need to use them in a string, you need to use \\ instead of \.

In your case, you should do

'D:\\myfiles\\test'.replace('\\','/')

Replacing backslash '\' in python

That's because \123 and \456 are special characters(octal).
Try this:

a = r'70\123456'
b = r'70\123\456'

a = a.replace('\\','-')
b = b.replace('\\','-')

print(a)
print(b)


Related Topics



Leave a reply



Submit