-1

I am trying to remove the backslash from a string but because the character is special it won't work. I want it to print "example".

example = ("e\x\m\p\l\e")
example=example.replace("\","")
print(example)
Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35
POVEY
  • 27
  • 6

2 Answers2

2
example = (r"e\x\m\p\l\e")
example=example.replace("\\","")

You can use a literal string using r, and then use replace with the special character using \\ (double backslash).

EDIT:

One can also use regex to remove all \:

import re
''.join(re.findall(r'[^\\]', example))

The findall will result in an list with all characters. You can use join to transform this list to a string.

''.join(re.findall(r'[^\\]', r'e\x\m\p\l\e this is an \exmaple. \\ test'))
>>> exmple this is an exmaple.  test
3dSpatialUser
  • 2,034
  • 1
  • 9
  • 18
1

You should use double \ to escape the special symbol:

example=example.replace("\\","")
Simas Joneliunas
  • 2,890
  • 20
  • 28
  • 35