小编Den*_*ura的帖子

比较字符串中的字符

我正在尝试创建一个函数,该函数比较两个长度相同的字符串的相同位置的字符并返回它们的差异计数。

例如,

a = "HORSE"
b = "TIGER"
Run Code Online (Sandbox Code Playgroud)

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

这就是我一直在做的事情。

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

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

所以我尝试使用 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
Run Code Online (Sandbox Code Playgroud)

这也返回相同的错误。

当我打印 list(one)[1] != list(two)[1] 时,它要么返回 True 要么返回 False,因为比较是正确进行的。

你能告诉我如何为此目的更正我的代码吗?

python string comparison character python-3.x

2
推荐指数
1
解决办法
3万
查看次数

标签 统计

character ×1

comparison ×1

python ×1

python-3.x ×1

string ×1