如何将python字符串中的\'替换为'

2024-05-21 00:19:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过从reddit中提取的文本进行解析,并将其清理为nlp,但是文本在每个引号前都有反斜杠。当我尝试使用字符串.替换然而,似乎没有任何影响,保持不变

print(submission.selftext.replace('\n','').replace('\\\'','\''))

很明显,replace本身没有问题,它可以很好地删除结束行。我如何让你认出这些字符?你知道吗


Tags: 字符串文本submissionnlp字符replace引号print
2条回答

如果你对使用regex没问题,你可以试试这个-

import re
a = "123123\\'\\'213\\'as"
a = re.sub(r'\\(?=\')', '', a)

给出123132''213'as

假设您只想替换后跟单引号的反斜杠,而不是全部。你知道吗

您可以编写chr(92)来替换\

>>> print(chr(92))
\                

https://docs.python.org/3/library/functions.html#chr

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

相关问题 更多 >