See Jamie Zawinksi's famous quote about regular expressions. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.
The actual content of string str (bad name for a variable, by the way, since there's a built-in type of that name) is
"abc INC\","None", "0", "test"
Why not just
str.replace('\\"', '|"')
which will do exactly what you want.
Answer from holdenweb on Stack OverflowThe goal: 'apple' -> 'app\e'
This doesn't work:
>>> "apple".replace('l', '\\')
'app\\e'This also doesn't work:
>>> "apple".replace('l', '\')
File "<stdin>", line 1
"apple".replace('l', '\')
^
SyntaxError: EOL while scanning string literalSee Jamie Zawinksi's famous quote about regular expressions. Try to only resort to the use of re's when absolutely necessary. In this case, it isn't.
The actual content of string str (bad name for a variable, by the way, since there's a built-in type of that name) is
"abc INC\","None", "0", "test"
Why not just
str.replace('\\"', '|"')
which will do exactly what you want.
You can use the following positive lookahead assertion '\\(?=")':
import re
my_str = "\"abc INC\\\",\"None\", \"0\", \"test\""
p = re.sub(r'\\(?=")', '|', my_str)
print(p)
# '"abc INC|","None", "0", "test"'
Try not to use builtin names as names for variables, viz. str, to avoid shadowing the builtin.
how to replace back slash character with empty string in python - Stack Overflow
string - python replace single backslash with double backslash - Stack Overflow
string - python replace backslashes to slashes - Stack Overflow
python - python3 replacing double backslash with single backslash - Stack Overflow
We need to specify that we want to replace a string that contains a single backslash. We cannot write that as "\", because the backslash is escaping the intended closing double-quote. We also cannot use a raw string literal for this: r"\" does not work.
Instead, we simply escape the backslash using another backslash:
result = string.replace("\\","")
The error is because you did not add a escape character to your '\', you should give \\ for backslash (\)
In [147]: foo = "a\c\d" # example string with backslashes
In [148]: foo
Out[148]: 'a\\c\\d'
In [149]: foo.replace('\\', " ")
Out[149]: 'a c d'
In [150]: foo.replace('\\', "")
Out[150]: 'acd'
No need to use str.replace or string.replace here, just convert that string to a raw string:
>>> strs = r"C:\Users\Josh\Desktop\20130216"
^
|
notice the 'r'
Below is the repr version of the above string, that's why you're seeing \\ here.
But, in fact the actual string contains just '\' not \\.
>>> strs
'C:\\Users\\Josh\\Desktop\\20130216'
>>> s = r"f\o"
>>> s #repr representation
'f\\o'
>>> len(s) #length is 3, as there's only one `'\'`
3
But when you're going to print this string you'll not get '\\' in the output.
>>> print strs
C:\Users\Josh\Desktop\20130216
If you want the string to show '\\' during print then use str.replace:
>>> new_strs = strs.replace('\\','\\\\')
>>> print new_strs
C:\\Users\\Josh\\Desktop\\20130216
repr version will now show \\\\:
>>> new_strs
'C:\\\\Users\\\\Josh\\\\Desktop\\\\20130216'
Let me make it simple and clear. Lets use the re module in python to escape the special characters.
Python script :
import re
s = "C:\Users\Josh\Desktop"
print s
print re.escape(s)
Output :
C:\Users\Josh\Desktop
C:\\Users\\Josh\\Desktop
Explanation :
Now observe that re.escape function on escaping the special chars in the given string we able to add an other backslash before each backslash, and finally the output results in a double backslash, the desired output.
Hope this helps you.
You can use the string .replace() method along with rawstring.
Python 2:
>>> print r'pictures\12761_1.jpg'.replace("\\", "/")
pictures/12761_1.jpg
Python 3:
>>> print(r'pictures\12761_1.jpg'.replace("\\", "/"))
pictures/12761_1.jpg
There are two things to notice here:
- Firstly to read the text as a drawstring by putting r before the string. If you don't give that, there will be a Unicode error here.
- And also that there were two backslashes given inside the replace method's first argument. The reason for that is that backslash is a literal used with other letters to work as an escape sequence. Now you might wonder what is an escape sequence. So an escape sequence is a sequence of characters that doesn't represent itself when used inside string literal or character. It is composed of two or more characters starting with a backslash. Like '\n' represents a newline and similarly there are many. So to escape backslash itself which is usually an initiation of an escape sequence, we use another backslash to escape it.
I know the second part is bit confusing but I hope it made some sense.
You can also use split/join:
print "/".join(r'pictures\12761_1.jpg'.split("\\"))
EDITED:
The other way you may use is to prepare data during it's retrieving(e.g. the idea is to update string before assign to variable) - for example:
f = open('c:\\tst.txt', "r")
print f.readline().replace('\\','/')
>>>'pictures/12761_1.jpg\n'
Take a closer look at the string, they are all single slash.
In [26]: my_str[0]
Out[26]: '\\'
In [27]: my_str[1]
Out[27]: 'x'
In [28]: len(my_str[0])
Out[28]: 1
And my_str.replace('\\','\') won't work because the token here is \', which escapes ' and waits for the another closing '.
Use my_str.replace('\\', '') instead
Update: after few more days, I realize the following discussion may also be helpful. If the intension of a string with escape ('\\x' or '\\u') are eventually hex/unicode literals, they can be decoded by escape_decode.
import codecs
print(len(b'\x32'), b'\x32') # 1 hex literal, '\x32' == '2'
print(len(b'\\x32'), b'\\x32') # 4 chars including escapes
print(codecs.escape_decode('\\x32', 'hex')) # chars->literal, 4->1
# 1 b'2'
# 4 b'\\x32'
# (b'2', 4)
s = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z'
ed, _ = codecs.escape_decode(s, 'hex')
print(len(s), s)
print(len(ed), ed)
# 49 \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z
# 22 b'\xa5\xc0\xe6aK\xf9\x80\xb1\xc8*\x01\x12$\xfbp\x1e(4\xd6{;Z'
If you do
s = '\\xa5\\xc0\\xe6aK\\xf9\\x80\\xb1\\xc8*\x01\x12$\\xfbp\x1e(4\\xd6{;Z\\x'
s = s.replace('\\','\')
print(s)
you get
File "main.py", line 3
s = s.replace('\\','\')
^
SyntaxError: EOL while scanning string literal
because in '\' the \ escapes the ' . Your string is left open.
You do not have any double \ in s - its just displaying it as such, do distinguish it from \ used to escape stuff if you inspect it.
If you print(s) you get \xa5\xc0\xe6aK\xf9\x80\xb1\xc8*$\xfbp(4\xd6{;Z\x
The difference between a string literal and a raw string is the way they are interpreted to create a string object from your source code. The objects they create are not distinct in any way. So there is no such thing as converting a string to a raw string.
In this case, '\018' stands for '\x01', which is the Start-of-Header character, followed by the character '8'.
chr(1) + '8' == '\x018' # True
And as you can see, your string contains no '\\' character.
'\\' in 'бекслеш \018 на точку' # False
I think you actually want to replace the control character:
Code
print(s.replace("\x01", ".01"))
# бекслеш .018 на точку
Details
It is clear that the programming language interprets the backslash as a control character.
Actually the control character includes the escape character (\) and the adjacent code (01). Let's see how Python looks at each character:
print(list(s))
# ['б', 'е', 'к', 'с', 'л', 'е', 'ш', ' ', '\x01', '8', ' ', 'н', 'а', ' ', 'т', 'о', 'ч', 'к', 'у']
Notice \x01 is one character, not the backslash alone. You have to replace this entire character.
Addendum
Therefore, a general approach can be to iterate each character and substitute any that belong to the control character category with a new string. This new string should be formatted to mirror the value of the character it replaces. Otherwise, return a normal character.
from unicodedata import category
"".join(".{:02d}".format(ord(char)) if category(char).startswith("C") else char for char in s)
# 'бекслеш .018 на точку'
- See also a list of unicode categories and this related post.
- See also this post on removing control characters.
So I have a string, and I want to remove all "words" in it, that have a backslash in them, like
'\t' '\t\t\t\t\t\t\t\t\t '
I can't use isalnum or similar, because the string also has chinese/russian characters, that i don't want to delete
Edit: thanks for the tips, I've got it now :)
I've tried str.replace("\\", "\") (reddit seems to reed 4 slashes as 2... Assume it's double the amount here) and str.replace(r"\", r""), it doesn't work.
Please help I'm desperate.
json_output = json.load(open(filepath))["subsection"][3]["intro"]
latex_output = ""
for paragraph in json_output:
latex_output += f"{paragraph}"
latex_output = ( latex_output.replace(r"\href", r"\href") .replace(r"\begin", r"\begin") .replace(r"\end", r"\end") .replace(r"\item", r"\item") )
print(latex_output)
Not sure if this is appropriate for your situation, but you could try using unicode_escape:
>>> t
'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
>>> type(t)
<class 'str'>
>>> enc_t = t.encode('utf_8')
>>> enc_t
b'\\u0048\\u0065\\u006c\\u006c\\u006f\\u0020\\u20ac\\u0020\\u00b0'
>>> type(enc_t)
<class 'bytes'>
>>> dec_t = enc_t.decode('unicode_escape')
>>> type(dec_t)
<class 'str'>
>>> dec_t
'Hello € °'
Or in abbreviated form:
>>> t.encode('utf_8').decode('unicode_escape')
'Hello € °'
You take your string and encode it using UTF-8, and then decode it using unicode_escape.
Since a backslash is an escape character and you are searching for two backslashes you need to replace four backslashes with two - i.e.:
t.replace("\\\\", "\\")
This will replace every r"\\" with r"\". The r indicates raw string. So, for example, if you type print(r"\\") into idle or any python script (or print r"\\" in Python 2) you will get \\\\. This means that every "\\" is really just a r"\".
user1632861 suggested that you use .replace("\\", ""), but this replaces ever r"\" with nothing. Try the above method instead. :D
In this case, however, it appears as though you are reading/receiving data, and you probably want to use the correct encoding and then decode to unicode (as the person above me suggested).