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

标签 python string python-3.x for-loop

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

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/

相关文章:

python - 创建子图,或在保留原始大小的同时合并图形

c# - 枚举可以包含字符串吗?

python - 有没有办法让 python str.partition 忽略大小写?

python - ModuleNotFoundError : No module named 'win10toast' ; bs4. FeatureNotFound:找不到具有您请求的功能的树生成器:lxml

Python3数据帧重组

python - 如何在 ffmpeg-python 的 filter_() 中使用输入参数?

python - 'getattr() : attribute name must be string' error in admin panel for a model with an ImageField

python - 如何改进从 2D numpy 数组中删除重复元素?

ruby-on-rails - 修剪字符尾随的零 n 轨

python - 列表中超过 1 个最长的字符串?