How to remove "" as string in python
Question:
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 = ("exmple")
example=example.replace("","")
print(example)
Answers:
You should use double to escape the special symbol:
example=example.replace("\","")
example = (r"exmple")
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'exmple this is an exmaple. \ test'))
>>> exmple this is an exmaple. test
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 = ("exmple")
example=example.replace("","")
print(example)
You should use double to escape the special symbol:
example=example.replace("\","")
example = (r"exmple")
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'exmple this is an exmaple. \ test'))
>>> exmple this is an exmaple. test