简体   繁体   English

从python中的两个字符串中一一删除字母

[英]Removing letters from two strings in python one by one

a = "ccdd"

b = "ccddcc"

I want to print:我想打印:

a = " "

b = 'cc'

By removing 'c' from both strings until no more 'c' left in any one of the string.通过从两个字符串中删除 'c' 直到任何一个字符串中都不再剩下 'c'。

Then remove 'd' as 'c' was removed然后删除“d”,因为“c”被删除

When you know exactly len(a) < len(b) , you can try this:当你确切地知道len(a) < len(b) ,你可以试试这个:

a = "ccdd"
b = "ccddcc"
while a and a[0] == b[0]:
     a = a[1:]
     b = b[1:]

Or you don't know which string will end first, try this:或者你不知道哪个字符串会先结束,试试这个:

while (a and b) and a[0] == b[0]:
     a = a[1:]
     b = b[1:]

Here are just the code written based on what you're providing, and remove by order.这里只是根据您提供的内容编写的代码,并按顺序删除。

Try this:尝试这个:

a = "ccdd"

b = "ccddcc"


def f(a, b):
    myList = list(set(a) & set(b))
    status = True
    while status == True:
        status = False
        if len(myList) > 0:
            status = True
            index1 = a.find(myList[0])
            index2 = b.find(myList[0])
            a = a[:index1] + a[index1 + 1:]
            b = b[:index2] + b[index2 + 1:]
            myList = list(set(a) & set(b))
    return a, b


a, b = f(a, b)

print(a)
print(b)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM