从字符串中删除数字

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

417500 次浏览

我很想使用正则表达式来完成这个任务,但是由于您只能使用列表、循环、函数等等..。

我是这么想的:

stringWithNumbers="I have 10 bananas for my 5 monkeys!"
stringWithoutNumbers=''.join(c if c not in map(str,range(0,10)) else "" for c in stringWithNumbers)
print(stringWithoutNumbers) #I have  bananas for my  monkeys!

这对你的情况有用吗?

>>> 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 和@kstrauser 所指出的,你实际上不需要使用一行程序中的括号,使得括号内的那一段成为一个生成器表达式(比列表内涵表达式更有效率)。即使这不符合你作业的要求,你最终也应该读一读:) :

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

如果我没理解错你的问题,一种方法是把字符串分解成字符然后用循环检查字符串中的每个字符是字符串还是数字然后如果字符串保存在变量中一旦循环结束,显示给用户

这个怎么样:

out_string = filter(lambda c: not c.isdigit(), in_string)

假设 st 是未格式化的字符串,然后运行

st_nodigits=''.join(i for i in st if i.isalpha())

如上所述。 但我猜你需要一些非常简单的东西 假设 <是的trong>是的是你的字符串 好的是一个没有数字的字符串,这是你的代码

l = ['0','1','2','3','4','5','6','7','8','9']
st_res=""
for ch in s:
if ch not in l:
st_res+=ch

不知道你老师允不允许你用过滤器,但是..。

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

报税表-

'aaasdffgh'

比循环更有效率。

例如:

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

只有一些(其他人提出了一些建议)

方法一:

''.join(i for i in myStr if not i.isdigit())

方法二:

def removeDigits(s):
answer = []
for char in s:
if not char.isdigit():
answer.append(char)
return ''.join(answer)

方法三:

''.join(filter(lambda x: not x.isdigit(), mystr))

方法四:

nums = set(map(int, range(10)))
''.join(i for i in mystr if i not in nums)

方法五:

''.join(i for i in mystr if ord(i) not in range(48, 58))

顺便说一句,经常被遗忘的 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'