简体   繁体   English

替换字符串中的特殊字符时出现问题

[英]Problem with Replacing special characters in a string

I am trying to feed some text to a special pupose parser. 我试图将一些文本提供给一个特殊的pupose解析器。 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. 所以使用str.replace我用来附加\\到所有这些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? 谁能为我提供解决这些角色的解决方案?

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 \\\\ . 这是Python通过向您显示反斜杠已转义为\\\\来告诉您该字符串包含文字\\的方法。

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)' . 您可能希望看到print 'abcdef\\\\(1234)'时看到的内容。 What you want is what you already have. 你想要的就是你已经拥有的。

That's just how escaped characters (like backslashes) are printed in the REPL. 这就是如何在REPL中打印转义字符(如反斜杠)。 The actual value of the string is as you expected. 字符串的实际值与您预期的一样。

>>> a = '\('
>>> a
'\\('
>>> print(a)
\(
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... 等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM