比较字符串中的字符

3

我将尝试创建一个函数来比较两个长度相同的字符串中相同位置的字符,并返回它们不同之处的数量。

例如,

a = "HORSE"
b = "TIGER"

它将返回5(因为同一位置的所有字符都不同)

这是我一直在努力的。

def Differences(one, two):
    difference = []
    for i in list(one):
        if list(one)[i] != list(two)[i]:
            difference = difference+1
    return difference

出现了错误“列表索引必须是整数而不是字符串”

所以我尝试使用int(ord())将其转换为整数

def Differences(one, two):
    difference = 0
    for i in list(one):
        if int(ord(list(one)[i])) != int(ord(list(two)[i])):
            difference = difference+1
    return difference

这也返回相同的错误。

当我打印“list(one)[1] != list(two)[1]”时,它会返回True或False,因为比较是正确的。

你能告诉我如何纠正我的代码以实现这个目的吗?


你收到错误的原因是因为你正在使用for循环迭代字符串。在Python中,当你迭代某样东西时(另外说一句,你不需要将字符串转换为列表;在Python中,字符串本来就是可迭代的),你会得到该项中的每个子项(而不是索引号)。因此,在你的for循环中,你得到了["H","O","R","S","E"]作为“i”的值,这显然不是索引(即0、1、2、3、4)。 - Reid Ballard
11个回答

0
a = "HORSE"
b = "TIGER"
a_list=[]
b_list=[]
for l in a_list:
    a_list.append(l)

for k in b_list:
    b_list.append(k)

difference = len(a)
for i in a_list:
    for x in b_list:
        if a_list[i] == b_list[x]:
            difference = difference - 1

print(difference)

看看这个是否有效 :)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接