从字符串中删除数字

2024-03-29 09:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

如何从字符串中删除数字?


Tags: 字符串数字
3条回答

这对你的情况有用吗?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

这利用了列表理解,这里发生的事情与此结构类似:

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

正如@AshwiniChaudhary和@KirkStrauser所指出的,实际上不需要在一行中使用括号,使括号内的部分成为生成器表达式(比列表理解更有效)。即使这不符合你的作业要求,你最终还是应该读一读:):

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

而且,只要把它放在一起,就是经常被遗忘的str.translate,它的工作速度比循环/正则表达式快得多:

对于Python 2:

from string import digits

s = 'abc123def456ghi789zero0'
res = s.translate(None, digits)
# 'abcdefghizero'

对于Python 3:

from string import digits

s = 'abc123def456ghi789zero0'
remove_digits = str.maketrans('', '', digits)
res = s.translate(remove_digits)
# 'abcdefghizero'

不确定你的老师是否允许你使用过滤器,但是。。。

filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")

返回-

'aaasdffgh'

比循环更有效率。。。

示例:

for i in range(10):
  a.replace(str(i),'')

相关问题 更多 >