删除数字字符串python

Mou*_*yer 3 python string

对于我的赋值,我必须创建一个函数,该函数返回一个与给定字符串相同但删除了数字的新字符串.

示例:删除数字('abc123')将返回字符串'abc'.

我已经尝试了几乎所有我能想到的但是它不能正常工作:(

def test(str):
    for ch in str:
        num = ['0', '1', '2', '3', '4', '6', '7', '8', '9']
        if ch == num[0]:
            return str.replace(ch, '')
        elif ch == num[1]:
            return str.replace(ch, '')
        elif ch == num[2]:
            return str.replace(ch, '')
        elif ch == num[3]:
            return str.replace(ch, '')
        elif ch == num[4]:
            return str.replace(ch, '')
        elif ch == num[5]:
            return str.replace(ch, '')
        elif ch == num[6]:
            return str.replace(ch, '')
        elif ch == num[7]:
            return str.replace(ch, '')
        elif ch == num[8]:
            return str.replace(ch, '')
Run Code Online (Sandbox Code Playgroud)

我输入test('abc123'),期望输出为'abc'.但相反,我得到'abc23'作为我的输出.

在其他尝试中,同样的问题:

def test(str):
    for char in str:
        num = ['0', '1', '2', '3', '4', '6', '7', '8', '9']
        if char in list(num):
            return str.replace(char, '', len(str))
Run Code Online (Sandbox Code Playgroud)

我得到了相同的结果.

谁能帮我?这将不胜感激.

R.M*_*.M. 6

使用正则表达式

import re
def test(str):
    string_no_numbers = re.sub("\d+", " ", str)
    print(string_no_numbers)
test('abc123') #prints abc
Run Code Online (Sandbox Code Playgroud)