如何在python中使用字符串保持标点符号?
发布时间:2020-12-20 12:37:51 所属栏目:Python 来源:网络整理
导读:我想创建所有日志的目录,所以我只想保留所有标点符号并删除所有其他包含CJK和其他字符的字符. 例如: s = "aaa; sf = fa = bla http://wa" 预期产量是 ;==:// 解决方法 你可以使用 str.translate : from string import letters,digits,whitespace,punctuati
|
我想创建所有日志的目录,所以我只想保留所有标点符号并删除所有其他包含CJK和其他字符的字符.
例如: s = "aaa; sf = fa = bla http://wa" 预期产量是 ;==:// 解决方法
你可以使用
str.translate:
>>> from string import letters,digits,whitespace,punctuation >>> s = "aaa; sf = fa = bla http://wa" >>> s.translate(None,letters+digits+whitespace) ';==://' 或正则表达式: >>> re.sub(r'[^{}]+'.format(punctuation),'',s)
';==://'
时间比较: >>> s = "aaa; sf = fa = bla http://wa"*1000
>>> %timeit s.translate(None,letters+digits+whitespace)
10000 loops,best of 3: 171 us per loop #winner
>>> r1 = re.compile(r'[^{}]+'.format(punctuation))
>>> r2 = re.compile(r'[ws]+')
>>> %timeit r1.sub('',s)
100 loops,best of 3: 2.64 ms per loop
>>> %timeit r2.sub('',best of 3: 3.31 ms per loop
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
