问题:从字符串中删除数字

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

How can I remove digits from a string?


回答 0

这适合您的情况吗?

>>> 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'

Would this work for your situation?

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

This makes use of a list comprehension, and what is happening here is similar to this structure:

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)

As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn’t fit the requirements for your assignment, it is something you should read about eventually :) :

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

回答 1

而且,经常把它丢进去,是经常被遗忘的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'

And, just to throw it in the mix, is the oft-forgotten str.translate which will work a lot faster than looping/regular expressions:

For Python 2:

from string import digits

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

For Python 3:

from string import digits

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

回答 2

不知道您的老师是否允许您使用过滤器,但是…

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

返回-

'aaasdffgh'

比循环更有效率…

例:

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

Not sure if your teacher allows you to use filters but…

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

returns-

'aaasdffgh'

Much more efficient than looping…

Example:

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

回答 3

那这个呢:

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

What about this:

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

回答 4

只是几个(其他人建议了其中一些)

方法1:

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

方法2:

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

方法3:

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

方法4:

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

方法5:

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

Just a few (others have suggested some of these)

Method 1:

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

Method 2:

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

Method 3:

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

Method 4:

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

Method 5:

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

回答 5

说st是您的未格式化的字符串,然后运行

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

正如刚才提到的。但是我猜想您需要非常简单的内容,所以说s是您的字符串,st_res是没有数字的字符串,那么这是您的代码

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

Say st is your unformatted string, then run

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

as mentioned above. But my guess that you need something very simple so say s is your string and st_res is a string without digits, then here is your code

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

回答 6

我很乐意使用正则表达式来完成此操作,但是由于您只能使用列表,循环,函数等。

这是我想出的:

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!

I’d love to use regex to accomplish this, but since you can only use lists, loops, functions, etc..

here’s what I came up with:

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!

回答 7

如果我正确理解您的问题,一种方法是将字符串分解为chars,然后使用循环检查该字符串中的每个char是字符串还是数字,然后将string保存到变量中,然后循环一次完成后,向用户显示

If i understand your question right, one way to do is break down the string in chars and then check each char in that string using a loop whether it’s a string or a number and then if string save it in a variable and then once the loop is finished, display that to the user


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。