Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python—返回一个字符串的函数,该字符串从另一个字符串中删除字符_Python_String_Replace - Fatal编程技术网

Python—返回一个字符串的函数,该字符串从另一个字符串中删除字符

Python—返回一个字符串的函数,该字符串从另一个字符串中删除字符,python,string,replace,Python,String,Replace,我接近了吗 str1和str2包含变量字符串 到目前为止,我的产量为21吨 所需输出为21mdnRmvhiwh使用列表理解: """Return a copy of str1 with characters from str2 removed. filter_string(string, string) -> string """ for a in str1: if a in str2: str1.replace(a,"") return str1 使用以下方法

我接近了吗

str1和str2包含变量字符串

到目前为止,我的产量为21吨


所需输出为21mdnRmvhiwh

使用列表理解:

"""Return a copy of str1 with characters from str2 removed.

filter_string(string, string) -> string
"""

for a in str1:
    if a in str2:
      str1.replace(a,"")

return str1

使用以下方法可以非常简单地编写函数:

这将从
str1
中删除
str2
中的所有字符

例如:

str1 = str1.translate(None, str2)

作为补充说明,您可以使用以下内容:
str1=str1.translate(None,str2)
boom绝对是传奇^祝您好运,先生。在Python 3中:
str1=re.sub('[%s]'%re.escape(str2),'',str1)
(忽略由多个Unicode码点组成的字符的问题)。
str1 = str1.translate(None, str2)
>>> 'Hello, world!'.translate(None, 'lewf!')
Ho, ord