Skip to main content
 首页 » 编程设计

python之从字符串python中删除数字

2025年05月04日1698°冷暖

我想从字符串中删除除字典中给出的数字之外的所有数字。我已经编写了删除它的代码 但没有得到预期的结果。请看下面:

mystr=" hey I want to delete all the digits ex 600 502 700 m 8745 given in this string. And getting request from the ip address 122521587502. This string tells about deleting digits 502 600 765 from this." 
 
myDict={'600','700'} # set() 
 
# snippet to remove digits from string other than digits given in the myDict  

我的解决方案

for w in myDict: 
    for x in mystr.split(): 
        if (x.isdigit()): 
            if(x != w): 
                mystr.replace(x," ") 

预期结果:

mystr=" hey I want to delete all the digits ex 600 700 m  given in this string. And getting request from the   
ip address . This string tells about deleting digits  600  from this." 

请您参考如下方法:

这是一种方法。

例如:

import string 
 
mystr= "hey I want to delete all the digits ex 600 502 700 m 8745 given in this string. And getting request from the  ip address 122521587502. This string tells about deleting digits 502 600 765 from this." 
mySet={'600','700'} 
 
rep = lambda x: x if x in mySet else None 
print( " ".join(filter(None, [rep(i) if i.strip(string.punctuation).isdigit() else i for i in mystr.split()])) ) 

输出:

hey I want to delete all the digits ex 600 700 m given in this string. And getting request from the ip address This string tells about deleting digits 600 from this.