且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从字符串中过滤字符

更新时间:2021-12-14 05:40:41

只需使用来自文档:

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)