python - 如何在 Python 中删除反斜杠和附加在反斜杠上的单词?

标签 python string

我知道删除一个反斜杠我们可能会做类似的事情
来自 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/

相关文章:

swift - 如何在 Swift 3 中将字符串转换为没有时间的日期?

Javascript TRUE 和 "true"为什么有人使用字符串而不是 boolean 值?

python - 跟踪周期,同时向稀疏图中添加随机边

python - 如何使用 HTTP Basic Auth 注释测试 Flask 路由方法

c++ - 忽略几个不同的词.. c++?

c# - 检查字符串是否仅包含 C# 中的数字的最快方法

python - 基于系列条件创建新的 pandas 列

python - OS X 服务器 : Using wsgi Python on Non-Standard Ports

Python Pickle 在 Windows 中加载时崩溃

c - fopen 未打开文件