【发布时间】:2018-08-23 18:03:45
【问题描述】:
我想从字符串中删除字典中给出的数字以外的所有数字。我已经编写了代码来删除它 但没有得到预期的结果。请看下面:
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."
【问题讨论】:
-
你的字典是一套吗?
-
@BallpointBen,是的。谢谢,我会编辑问题。
-
这不是字典而是集合,您可以使用
in运算符检查成员资格,而不是循环遍历集合。此外,永远不要更改您正在循环的迭代器。
标签: python string python-3.x for-loop