如何在 Python 3 中比较两个字符串中的单个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35328953/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:18:10  来源:igfitidea点击:

How to compare individual characters in two strings in Python 3

pythonstringpython-3.x

提问by Hymanie

I'm trying to compare the first character of two different strings (and so on) to form a new string based on those results. This is what I've tried using, however its comparing every element of each list to each other.

我正在尝试比较两个不同字符串(等等)的第一个字符,以根据这些结果形成一个新字符串。这是我尝试使用的,但是它将每个列表的每个元素相互比较。

def compare(a,b):
    s = ""
    for x in a:
        for y in b:
            if x == y:
                s+=str(x)
            else:
                s+=str(y)

It seems like such a simple question but I'm stuck.

这似乎是一个如此简单的问题,但我被卡住了。

采纳答案by L3viathan

Use zip:

使用邮编:

def compare(a, b):
    for x, y in zip(a, b):
        if x == y:
            ...

回答by Prune

Are you perhaps looking for something with logic similar to this? It chooses the alphabetically earlier character from each input string:

您是否正在寻找与此逻辑类似的东西?它从每个输入字符串中选择按字母顺序较早的字符:

def compare(a,b):
    s = ""
    for i in range(len(a)):
        if a[i] < b[i]:
            s+=str(a[i])
        else:
            s+=str(b[i])
    return s

print compare ("seven", "eight")

Output:

输出:

eegen


The one-line version of this is

这个的单行版本是

return ''.join(a[i] if a[i] < b[i] else b[i] for i in range(len(a)))

回答by Newb_01

input(x)
input(y)
cnt = 0
 for char_val in x:
   if b[cnt] == char_val:
      print("match")
   else:
      print("mis-match")