有没有其他方法可以解决 python 中的 Remove character?

Is there any alternative method to solve Remove character in python?

Consider two strings s1 and s2,you have to write a static function which takes s1 and s2 strings as arguments and removes the characters from the first string, which are present in the second string. For example, if the first String "India is great" and second String is "in" then the output should be "da s great".

输入格式

First line should contain string s1. Second line should contain string s2.

Constraints

1<=N<=1000

Output Format

Output string

Sample Input 0

    India is great
    in

Sample Output 0

    da s great

Sample Input 1

    Hello all how are you
    are

Sample Output 1

    Hllo ll how you

我的代码

lst = [i for i in input()]
check = [i for i in input()]

for i in check:
    for j in lst:
        if i == j or i.upper() == j:
            lst.remove(j)
       
    
for i in lst:
    print(i,end='')

我的输出

da s great

我的输出 2 是错误的,如果 are 被删除它会留下一个额外的 space

Hllo ll how  you

您永远不应该修改您循环访问的列表。 相反,您可以生成一个不包含禁用字符的新字符串。 此外,为了使该算法更有效,您可以将所有禁止使用的字符存储在一个集合中。

input_s = input() # No need to loop over the lists here.
forbidden_chars = {c.lower() for c in input()}
new_s = ''.join([char in input_s if char.lower() not in forbidden_chars])
print(new_s)

看起来您只需将字符串中包含两个 space 的部分替换为一个 space。当删除整个单词时,会出现两种 space 的情况。

import re

lst = input()
check = [str.lower(c) for c in input()]
upper_check = [str.upper(c) for c in check]

for i in range(len(check)):
      lst = lst.replace(check[i], '')
      lst = lst.replace(upper_check[i], '')

lst = re.sub(r"\s+", ' ', lst)
print(lst.strip())

过滤列表理解中的字符并使用连接将结果放回原处:

def remove(s1,s2):
    return "".join(c for c in s1 if c.lower() not in s2.lower())
    
print(remove("India is great","in"))
# da s great

您也可以通过构建大小写字母列表来使用翻译来删除:

def remove(s1,s2):
    exclude = str.maketrans("","",s2.lower()+s2.upper())
    return s1.translate(exclude)

可以通过拆分和重建字符串来删除连续的空格:

return " ".join(s1.translate(exclude).split())