如何从字符串列表中删除所有转义序列? [英] How to remove all the escape sequences from a list of strings?

查看:63
本文介绍了如何从字符串列表中删除所有转义序列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从字符串列表中删除所有类型的转义序列.我怎样才能做到这一点?输入:

['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray']

输出:

['william', 'short', 'twitter', 'video', 'guy', 'ray']

http://docs.python.org/reference/lexical_analysis.html#字符串文字

解决方案

类似的事情?

<预><代码>>>>从 ast 导入literal_eval>>>s = r'你好,\n世界!'>>>打印(literal_eval('%s'"%s))你好,世界!

编辑:好的,这不是您想要的.您想要的东西通常无法完成,因为正如@Sven Marnach 所解释的那样,字符串实际上并不包含转义序列.这些只是字符串文字中的符号.

您可以使用

从列表中过滤所有包含非 ASCII 字符的字符串

def is_ascii(s):尝试:s.decode('ascii')返回真除了 UnicodeDecodeError:返回错误[s for s in ['william', 'short', '\x80', 'twitter', '\xaa','\xe2', 'video', 'guy', 'ray']如果 is_ascii(s)]

I want to remove all types of escape sequences from a list of strings. How can I do this? input:

['william', 'short', '\x80', 'twitter', '\xaa', '\xe2', 'video', 'guy', 'ray']

output:

['william', 'short', 'twitter', 'video', 'guy', 'ray']

http://docs.python.org/reference/lexical_analysis.html#string-literals

解决方案

Something like this?

>>> from ast import literal_eval
>>> s = r'Hello,\nworld!'
>>> print(literal_eval("'%s'" % s))
Hello,
world!

Edit: ok, that's not what you want. What you want can't be done in general, because, as @Sven Marnach explained, strings don't actually contain escape sequences. Those are just notation in string literals.

You can filter all strings with non-ASCII characters from your list with

def is_ascii(s):
    try:
        s.decode('ascii')
        return True
    except UnicodeDecodeError:
        return False

[s for s in ['william', 'short', '\x80', 'twitter', '\xaa',
             '\xe2', 'video', 'guy', 'ray']
 if is_ascii(s)]

这篇关于如何从字符串列表中删除所有转义序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆