繁体   English   中英

如何在2个字符串中找到相同的字符?

[英]How to find same characters in 2 string?

我有 2 个字符串

c = "The quick brown brown fox did jump a"
c1 = "The brown did fox"

我正在尝试使用字符串 c 来搜索 c1 并找到相似的字母。 如果找到相似的字母,则应将其删除并添加到新字符串中。 删除时,它应该删除直到并包括该字符的所有字母。

当您执行此过程时,您应该获得由“Theiox”组成的新字符串

它可能是这样的:

c = "The quick brown brown fox did jump a".replace(" ", "")
c1 = "The brown did fox".replace(" ", "")

new_str = ""
for letter in c:
    index = c1.find(letter)
    if index != -1:
        new_str = new_str + letter
        c1 = c1[index+1:]

print(new_str)

首先删除空格,因为您不希望它出现在新字符串中。

然后在字符串 c1 中搜索 c 字母的出现,如果找到,将它们添加到 new_string 并更改c1 = c1[index+1:]中的c1 = c1[index+1:]以删除部分直到找到的字符。

希望能帮助到你。

暂无
暂无

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

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