问题描述
我正在比较两个字符串,例如'beacon'和'becon'。我本质上是希望函数告诉我,在“信标”的索引2处,列表形式有所不同。我目前拥有的是:
word1 = 'beacon'
word2 = 'becon'
list = []
for i in range(len(word1)):
if word1[i] != word2[i]:
list.append(i)
return list
但是我得到IndexError: string index out of range
,因为word1比word2长。切换单词不是一个选择,因为如果我要比较“ beconn”和“ becon”这样的字符串,我希望程序返回索引5。我怎么能解决这个问题而不导入任何东西?
(理想情况下,该解决方案也可以使用偶数长度的字符串(例如,将“ becon”与“ bacon”进行比较),并且如果存在多个差异,则将返回索引列表。)
编码方面的新功能,非常感谢看到这个的人!
解决方法
使用zip()
或zip_longest()
来满足两个str的不均匀长度:
word1 = 'beacon'
word2 = 'becon'
chrs_lst = []
indx_lst = []
for indx,(w1,w2) in enumerate(zip(word1,word2)):
if w1 != w2:
chrs_lst.append(w1)
indx_lst.append(indx)
print(chrs_lst)
print(indx_lst)
输出:
['a','c','o','n']
[2,3,4,5]