Python 从字符串中过滤字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18173555/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Filtering Characters from a String
提问by SunshineTS
I need to make a function that takes two strings as imnput and returns a copy of str 1 with all characters from str2 removed.
我需要创建一个函数,该函数将两个字符串作为输入并返回 str 1 的副本,其中删除了 str2 中的所有字符。
First thing is to iterate over str1 with a for loop, then compare to str2, to accomplish subtraction I should create a 3rd string in which to store the output but I'm a little lost after that.
第一件事是用 for 循环遍历 str1,然后与 str2 进行比较,以完成减法我应该创建第三个字符串来存储输出,但在那之后我有点迷失了。
def filter_string(str1, str2):
str3 = str1
for character in str1:
if character in str2:
str3 = str1 - str2
return str3
This is what I've been playing with but I don't understand how I should proceed.
这是我一直在玩的,但我不明白我应该如何进行。
采纳答案by NPE
Just use str.translate()
:
只需使用str.translate()
:
In [4]: 'abcdefabcd'.translate(None, 'acd')
Out[4]: 'befb'
From the documentation:
从文档:
string.translate(s, table[, deletechars])
Delete all characters from
s
that are indeletechars
(if present), and then translate the characters usingtable
, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. Iftable
is None, then only the character deletion step is performed.
string.translate(s, table[, deletechars])
删除所有字符从
s
是在deletechars
(如果存在的话),然后翻译使用的字符table
,它必须是256个字符的字符串,给出了翻译的每个字符值,其序索引。如果table
是 None,则只执行字符删除步骤。
If -- for educational purposes -- you'd like to code it up yourself, you could use something like:
如果 - 出于教育目的 - 您想自己编写代码,您可以使用以下内容:
''.join(c for c in str1 if c not in str2)
回答by lecodesportif
Use replace
:
使用replace
:
def filter_string(str1, str2):
for c in str2:
str1 = str1.replace(c, '')
return str1
Or a simple list comprehension:
或者一个简单的列表理解:
''.join(c for c in str1 if c not in str2)