我想从字符串中删除除字典中给出的数字之外的所有数字。我已经编写了删除它的代码 但没有得到预期的结果。请看下面:
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.
关于python - 从字符串python中删除数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51991800/