簡體   English   中英

從python中的兩個字符串中一一刪除字母

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

a = "ccdd"

b = "ccddcc"

我想打印:

a = " "

b = 'cc'

通過從兩個字符串中刪除 'c' 直到任何一個字符串中都不再剩下 'c'。

然后刪除“d”,因為“c”被刪除

當你確切地知道len(a) < len(b) ,你可以試試這個:

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

或者你不知道哪個字符串會先結束,試試這個:

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

這里只是根據您提供的內容編寫的代碼,並按順序刪除。

嘗試這個:

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