删除两个字符串中的公共字符

huangapple go评论71阅读模式
英文:

python, delete common characters from two strings

问题

以下是您提供的代码的翻译部分:

给定两个字符串假设为stringA和stringBlen(stringA)>len(stringB)),如何从stringA中删除所有出现在stringB中的字符假定stringB中的所有字符都出现在stringA中

以下是我尝试过的代码

```python
a = input()
b = input()

for i in range(len(b)):
    if b[i] not in a:
        a.remove(b[i])

我期望它会从A中删除字符,但却导致了一个错误。我是Python的初学者,对于在这里应该使用哪种其他方法或途径一无所知。

不要翻译的部分已被省略。如果您有任何其他问题或需要进一步的帮助,请随时提出。

<details>
<summary>英文:</summary>

Given two strings suppose stringA and stringB (len(stringA)&gt;len(stringB)), how do i remove all characters from stringA which are present in stringB? Assume that all characters in stringB are present in stringA

Here is what i tried:

a=input()
b=input()

for i in range(len(b)):
if b[i] not in a:
a.remove(b[i])




I expected it to remove characters from A, but resulting in an error, I am a beginner in python and i havent a clue which other method or approach i should use here

</details>


# 答案1
**得分**: 1

使用`set`来提高效率,并使用列表推导式循环遍历A的所有字符进行过滤和[`join`](https://docs.python.org/3/library/stdtypes.html#str.join):
```python
s = set(B)
out = ''.join([c for c in A if not c in s])
英文:

Use a set of B for efficiency and loop over all characters of A with a list comprehension to filter and join them:

s = set(B)
out = &#39;&#39;.join([c for c in A if not c in s])

答案2

得分: 1

stringA = input()
stringB = input()

for char in stringB:
stringA = stringA.replace(char, "")

print(stringA)

英文:
stringA = input()
stringB = input()

for char in stringB:
    stringA = stringA.replace(char, &quot;&quot;)

print(stringA)  

答案3

得分: 1

s1 = input()
s2 = input()
new_s1 = ""
new_s2 = ""
for char in s1:
if char not in s2:
new_s1 += char

for char in s2:
if char not in s1:
new_s2 += char

print(new_s1)
print(new_s2)

英文:
s1 = input()
s2 = input()
new_s1 = &quot;&quot;
new_s2 = &quot;&quot;
for char in s1:
    if char not in s2:
        new_s1 += char

for char in s2:
    if char not in s1:
        new_s2 += char

print(new_s1)  
print(new_s2) 

答案4

得分: 0

str对象没有名为remove的方法。你需要使用类似replace或使用set来提高效率:

out = "".join(set(a).difference(set(b)))

请注意,这不一定会保持字符串A中字符的顺序。

英文:

str object has no method called remove. You have to use sth like replace or use set for efficiency:

out = &quot;&quot;.join(set(a).difference(set(b)))

Note that this will not necessarily maintain order of the characters of A.

huangapple
  • 本文由 发表于 2023年2月16日 14:58:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75468791.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定