prosseek
prosseek

Reputation: 190809

Replace single backslash into double backslash with Python

I need to replace \ into \\ with python from pattern matching. For example, $$\a\b\c$$ should be matched replaced with $$\\a\\b\\c$$.

I couldn't use the regular expression to find a match.

>>> import re
>>> p = re.compile("\$\$([^$]+)\$\$")
>>> a = "$$\a\b\c$$"
>>> m = p.search(a)
>>> m.group(1)
'\x07\x08\\c'

I can't simply make the input as raw string such as a=r'$$\a\b\c$$' because it's automatically processed with markdown processor. I also found that I couldn't use replace method:

>>> a.replace('\\','\\\\')
'$$\x07\x08\\\\c$$'

How can I solve this issue?

Upvotes: 1

Views: 1489

Answers (2)

ollien
ollien

Reputation: 4766

The reason you're having trouble is because the string you're inputting is $$\a\b\c$$, which python translates to '$$\x07\x08\\c$$', and the only back slash in the string is actually in the segment '\c' the best way to deal with this would be to input a as such

a=r'$$\a\b\c$$'

This will tell python to convert the string literals as raw chars. If you're reading in from a file, this is done automatically for you.

Upvotes: 2

Michael Laszlo
Michael Laszlo

Reputation: 12239

Split the string with single backslashes, then join the resulting list with double backslashes.

s = r'$$\a\b\c$$'
t = r'\\'.join(s.split('\\'))
print('%s -> %s' % (s, t))

Upvotes: 0

Related Questions