英文:
python, delete common characters from two strings
问题
以下是您提供的代码的翻译部分:
给定两个字符串,假设为stringA和stringB(len(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)>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 = ''.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, "")
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 = ""
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)
答案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 = "".join(set(a).difference(set(b)))
Note that this will not necessarily maintain order of the characters of A.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论