【问题标题】:How do you remove backslashes and the word attached to the backslash in Python?如何在 Python 中删除反斜杠和附加到反斜杠的单词?
【发布时间】:2021-06-10 18:26:28
【问题描述】:

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

我不确定如何处理 '\' 后面的字符串,或者为什么它添加了一个新的 '\' 而不是删除它。

【问题讨论】:

  • 你试过什么?你在哪里卡住?根据How to Ask,Stack Overflow 通常希望您在发帖之前真诚地尝试自己满足您的要求。
  • 感谢@esqew 的反馈。我对此进行了尝试。我对 python 很陌生,所以我知道我的尝试是不正确的,但希望它能提供一些关于我在哪里的见解

标签: python string


【解决方案1】:

很难说服 Python 忽略 Unicode 字符。这是一个有点骇人听闻的尝试:

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 字符。因此,它不以反斜杠和 for 开头

[x for x in l if not x.startswith("\\")]

你得到

['Historical Notes 1996', '\ue606', 'The Future of farms 2012']

【讨论】:

  • 好的——这很有帮助。似乎 python 正在将 \ue606 之类的内容读取为 unicode 字符
  • @KatieMelosto Python 3 字符串根据定义总是 Unicode。
  • @BoarGules - 好的 - 谢谢我不知道!
【解决方案2】:

你可以用这个。
对 unicode 字符串使用 isprintable(),对以反斜杠开头的字符串使用 '\\'。

List = ['Historical Notes 1996','\ue606','The Future of farms 2012','\ch889','\8uuuu',]
print([x for x in List if x[0] != '\\' and x.isprintable()])

【讨论】:

猜你喜欢
  • 2010-12-14
  • 1970-01-01
  • 2021-10-23
  • 2018-07-26
  • 2016-06-16
  • 1970-01-01
  • 2013-06-24
  • 2012-02-10
相关资源
最近更新 更多