开发者

Problem with Replacing special characters in a string

I am tryi开发者_StackOverflow社区ng to feed some text to a special pupose parser. The problem with this parser is that it is sensitive to ()[] characters and in my sentence in the text have quite a lot of these characters. The manual for the parser suggests that all the ()[] get replaced with \( \) \[ \]. So using str.replace i am using to attach \ to all of those charcaters. I use the code below:

a = 'abcdef(1234)'
a.replace('(','\(')

however i get this as my output:

'abcdef\\(1234)'

What is wrong with my code? can anyone provide me a solution to solve this for these characters?


That's just how escaped characters (like backslashes) are printed in the REPL. The actual value of the string is as you expected.

>>> a = '\('
>>> a
'\\('
>>> print(a)
\(


Nothing is wrong with your code. This is Python's way to tell you that the string contains a literal \, by showing you that the backslash has been escaped as \\.

That way you can tell if you have two characters, a \ followed by (, or just one character, a escaped bracket \(.

You probably expected to see what you see when you do print 'abcdef\\(1234)'. What you want is what you already have.


suggests that all the ()[] get replaced with \( \) \[ \]

As i understand, parser itself make the replacement, so if you input:

'abcdef(1234)'

output will be:

'abcdef\(1234\)'

So you have to parse the output to get your original text with:

output.replace('\(','(').replace('\)',')')......

etc...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜