[英]Compare two string char by char in python and get unmatched character
我遇到了一個問題,我有兩個不同長度的字符串,一個字符串是第一個字符串的子集。
str1='usay'
str2='usy'
我需要以某種方式匹配這兩個字符串作為回報我得到's'的索引和字母'a',因為我需要go到字符's'的索引並在它之后添加一個'a'到匹配兩個字符串。 我將如何 go 這樣做?
首先,如果你想讓字符串匹配,為什么不直接設置 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 有更多字符。 我認為如果存在多個差異(例如 if str2 = uy
而不是usy
),它會工作得很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.