我知道删除一个反斜杠我们可能会做类似的事情
来自 Removing backslashes from a string in Python
我试图:
我想知道如何在下面的列表中删除所有像“\ue606”这样的词,
A =
['Historical Notes 1996',
'\ue606',
'The Future of farms 2012',
'\ch889',
'\8uuuu',]
将其转化为['Historical Notes 1996',
'The Future of farms 2012',]
我试过:A = ['Historical Notes 1996',
'\ue606',
'The Future of farms 2012',
'\ch889',
'\8uuuu',]
for y in A:
y.replace("\\", "")
A
它返回:['Historical Notes 1996',
'\ue606',
'The Future of farms 2012',
'\\ch889',
'\\8uuuu']
我不确定如何处理 '\' 后面的字符串,或者为什么它添加了一个新的 '\' 而不是删除它。
最佳答案
很难说服 Python 忽略 unicode 字符。这是一个有点hacky的尝试:
l = ['Historical Notes 1996',
'\ue606',
'The Future of farms 2012',
'\ch889',
'\8uuuu',]
def not_unicode_or_backslash(x):
try:
x = x.encode('unicode-escape').decode()
finally:
return not x.startswith("\\")
[x for x in l if not_unicode_or_backslash(x)]
# Output: ['Historical Notes 1996', 'The Future of farms 2012']
问题是你不能直接检查字符串是否以反斜杠开头,因为 \ue606
不被视为 6 个字符的字符串,而是作为单个 unicode 字符。因此,它不以反斜杠开头,对于[x for x in l if not x.startswith("\\")]
你得到['Historical Notes 1996', '\ue606', 'The Future of farms 2012']
关于python - 如何在 Python 中删除反斜杠和附加在反斜杠上的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67926656/