从 python 字符串中删除 \n

Remove \n from python string

我用美汤抓取了一个网页。 我试图摆脱一个 '\n' 字符,尽管我尝试了它,但它并没有被消除。

我目前的努力:

wr=str(loc[i-1]).strip()
wr=wr.replace(r"\[|'u|\n","")
print(wr)

输出:

    [u'\nWong; Voon Hon (Singapore, SG
Kandasamy; Ravi (Singapore, SG
Narasimalu; Srikanth (Singapore, SG
Larsen; Gerner (Hinnerup, DK
Abeyasekera; Tusitha (Aarhus N, DK

如何消除[u'\n?我做错了什么?

完整代码为here

您需要转义反斜杠或使用原始字符串。否则,它是换行符,而不是文字 \n

此外,我不认为 beautifulsoup 正在输出 unicode 字符串。您会看到 python 中的字符串表示形式为 u'blah'

而且您不需要要删除的元素列表。表达式可以是

r"\[|'u|\n"

您需要转义换行符(双“\”):

rep=["[","u'","\n"]
for r in rep:
    wr=wr.replace(r,"")

这与@cricket_007的回答相同,但是,他的回答的第二部分对我不起作用。据我所知,str.replace() 不支持这种正则表达式查找。