Sun*_*eTS 6 python string iteration
我需要创建一个函数,它接受两个字符串作为imnput,并返回str 1的副本,删除str2中的所有字符.
首先是使用for循环遍历str1,然后与str2进行比较,以完成减法我应该创建第3个字符串来存储输出,但之后我有点失落.
def filter_string(str1, str2):
str3 = str1
for character in str1:
if character in str2:
str3 = str1 - str2
return str3
Run Code Online (Sandbox Code Playgroud)
这就是我一直在玩的但我不明白我该怎么做.
NPE*_*NPE 18
只需使用str.translate():
In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'
Run Code Online (Sandbox Code Playgroud)
从文档:
Run Code Online (Sandbox Code Playgroud)string.translate(s, table[, deletechars])删除所有字符
s是在deletechars(如果存在的话),然后翻译使用的字符table,它必须是256个字符的字符串,给出了翻译的每个字符值,其序索引.如果table为"无",则仅执行字符删除步骤.
如果 - 出于教育目的 - 你想自己编写代码,你可以使用类似的东西:
''.join(c for c in str1 if c not in str2)
Run Code Online (Sandbox Code Playgroud)
使用replace:
def filter_string(str1, str2):
for c in str2:
str1 = str1.replace(c, '')
return str1
Run Code Online (Sandbox Code Playgroud)
或者一个简单的列表理解:
''.join(c for c in str1 if c not in str2)
Run Code Online (Sandbox Code Playgroud)