python中如何删除str1中与str2中相同的字母,留下str1剩下字母(用for loop)

如题所述

我直接上代码,这个你可能看不懂,这种叫推导式,可以自己学学,python适合这样做,代码很少。

str1 = 'abcdefg'
str2 = 'bdehijkl'
#循环str1中的字符,如果没有在str2中找到,将c放到列表中,最后用''.join将列表变成字符串。
newstr1 = ''.join([ c for c in str1 if str2.find(c)< 0 ])
print newstr1

追问

如果用loop循环怎么写呢?
谢谢

追答

python里有loop吗?你说的是用for来loop吧。

str1 = 'abcdefg'
str2 = 'bdehijkl'
#newstr1 = ''.join([ c for c in str1 if str2.find(c)< 0 ])
newstr1 = '';
for c in str1:
    if (str2.find(c) < 0):
        newstr1 += c;
print newstr1

追问

谢谢

温馨提示:答案为网友推荐,仅供参考
相似回答