【问题标题】:Compare two string char by char in python and get unmatched character在python中逐个字符比较两个字符串并得到不匹配的字符
【发布时间】:2021-05-08 12:42:03
【问题描述】:

我遇到了一个问题,我有两个不同长度的字符串,一个字符串是第一个字符串的子集。

str1='usay'

str2='usy'

我需要以某种方式匹配这两个字符串作为回报我得到's'的索引和字母'a',因为我需要转到字符's'的索引并添加一个'a'在它之后匹配两个字符串。我将如何去做?

【问题讨论】:

标签: python algorithm nlp


【解决方案1】:

首先,如果您希望字符串匹配,为什么不直接设置 str2 = str1?也许这很容易,但也许不是。

否则,您可以遍历每个字符串中的字符并检查它们何时匹配。当您发现它们不匹配时,您可以设置字符串 2 以添加该字符,如下所示:

str1 = 'usay'
str2 = 'usy'

for n in range(0,int(len(str1))):
    if str1[n] == str2[n]: print(f'letter {n} is same!')
    if str1[n] != str2[n]:
        str2 = str2[:n] + str1[n] + str2[n:] #This takes all the characters before our 
                                             #difference shows, adds the difference character,
                                             #and then adds the characters after the difference
    
print(f'str1 is {str1}')
print(f'str2 is {str2}')

运行它给了我以下信息:

letter 0 is same!
letter 1 is same!
letter 3 is same!
str1 is usay
str2 is usay

此代码假定 str1 有更多字符。我认为如果存在多个差异(例如 str2 = uy 而不是 usy),它会很好地工作。

【讨论】:

    猜你喜欢
    • 2012-08-02
    • 2015-07-31
    • 2019-01-14
    • 1970-01-01
    • 2020-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多