从字符串中过滤字符 [英] Filtering Characters from a String

查看:447
本文介绍了从字符串中过滤字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要制作一个函数,将两个字符串作为输入,并返回str 1的副本,其中删除了str2中的所有字符.

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.

第一件事是使用for循环在str1上进行迭代,然后与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.

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.

推荐答案

只需使用来自文档:

string.translate(s, table[, deletechars])

删除deletechars 中的所有s字符(如果存在),然后使用table转换字符,该字符必须为256个字符的字符串,并提供以下内容的翻译每个字符值,按其序号索引. 如果table为None,则仅执行字符删除步骤.

Delete all characters from s that are in deletechars (if present), and then translate the characters using table, which must be a 256-character string giving the translation for each character value, indexed by its ordinal. If table is None, then only the character deletion step is performed.

如果出于教育目的,您想自己编写代码,则可以使用以下代码:

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)

这篇关于从字符串中过滤字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆