[英]How to compare individual characters in two strings in Python 3
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.这似乎是一个如此简单的问题,但我被卡住了。
Use zip:使用邮编:
def compare(a, b):
for x, y in zip(a, b):
if x == y:
...
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)))
input(x)
input(y)
cnt = 0
for char_val in x:
if b[cnt] == char_val:
print("match")
else:
print("mis-match")
Here is a complete function这里有一个完整的功能
def compare_strings(a,b):
result = True
if len(a) != len(b): print('string lengths do not match!')
for i,(x,y) in enumerate(zip(a,b)):
if x != y:
print(f'char miss-match {x,y} in element {i}')
result = False
if result: print('strings match!')
return result
def twoStrings(s1, s2):
for i in range(len(s1)):
for j in range(len(s2)):
if s2[j] == s1[i]:
return 'YES'
return 'NO'
We can write simple and easy method to compare similar letters in two strings我们可以编写简单易行的方法来比较两个字符串中的相似字母
def compare(a,b):
s = ""
t=""
for x in a:
for y in b:
if x == y:
t=x
s=s+t
print(s)
compare("xyz","axy")
Here first for loop
will compare each letters in string and display all similar character.这里第一个
for loop
将比较字符串中的每个字母并显示所有相似的字符。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.