【问题标题】:How to strip noisy pattern at the end of string?如何去除字符串末尾的嘈杂图案?
【发布时间】:2016-01-12 02:06:45
【问题描述】:

我有一个字符串列表(len 10000),其中一些看起来像

Belin (*) 9
München 12

我想去掉字符串末尾的数字和 (*) 以获得纯城市名称

Berlin
München

我可以使用 rstrip 吗?

【问题讨论】:

  • 您的城市是否超过 1 个字?

标签: python string python-2.7 python-3.x


【解决方案1】:

使用正则表达式函数 re.sub 删除 (*) (\(\*\)) 和带有额外前导空格 (\s*) 的数字 (\d+):

>>> cities = [
...     'Belin (*) 9',
...     'München 12',
...     'Los Angeles 9'
... ]
>>> [re.sub('\s*\(\*\)|\s*\d+', '', city) for city in cities]
['Belin', 'München', 'Los Angeles']

使用str.rstrip,需要指定所有要删除的字符:

>>> [city.rstrip(' 0123456789(*)') for city in cities]
['Belin', 'München', 'Los Angeles']

【讨论】:

    猜你喜欢
    • 2017-10-04
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2010-11-05
    • 1970-01-01
    相关资源
    最近更新 更多