栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何删除列表中的多个字符?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何删除列表中的多个字符?

使用

str.strip()
或最好
str.lstrip()

In [1]: x = ['+5556', '-1539', '-99','+1500']

使用

list comprehension

In [3]: [y.strip('+-') for y in x]Out[3]: ['5556', '1539', '99', '1500']

使用

map()

In [2]: map(lambda x:x.strip('+-'),x)Out[2]: ['5556', '1539', '99', '1500']

编辑:

如果您同时也在数字之间,请使用@Duncan提供的

str.translate()
基础解决方案。
+``-

使用string.translate(),或用于Python 3.x str.translate:

Python 2.x:

>>> import string>>> identity = string.maketrans("", "")>>> "+5+3-2".translate(identity, "+-")'532'>>> x = ['+5556', '-1539', '-99', '+1500']>>> x = [s.translate(identity, "+-") for s in x]>>> x['5556', '1539', '99', '1500']Python 2.x Unipre:>>> u"+5+3-2".translate({ord(c): None for c in '+-'})u'532'

Python 3.x版本:

>>> no_plus_minus = str.maketrans("", "", "+-")>>> "+5-3-2".translate(no_plus_minus)'532'>>> x = ['+5556', '-1539', '-99', '+1500']>>> x = [s.translate(no_plus_minus) for s in x]>>> x['5556', '1539', '99', '1500']


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/640596.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号