如何在python中按字符比较两个字符串并打印匹配位置

zyfwsgd6  于 2023-01-29  发布在  Python
关注(0)|答案(3)|浏览(178)

我想通过字符比较两个字符串,然后打印出它们在相同位置有相同字符的次数。如果我输入“soon”和“moon”作为两个字符串,它会打印出它们在3个位置匹配。我遇到了另一个问题,如果第二个字符串较短,它会给我一个错误“string index out of range”。我尝试了

a = input('Enter string')
b = input('Enter string')
i=0
count = 0

while i<len(a):
    if b[i] == a[i]:
      match = match + 1
    i = i + 1
print(match, 'positions.')
kpbwa7wx

kpbwa7wx1#

第二个if语句中有一些额外的代码,第一个if语句中没有match incrementor,也不需要found变量,这段代码应该可以解决这个问题

# get input from the user
A = input('Enter string')
B = input('Enter string')

# set the incrementors to 0
i=0
match = 0

# loop through every character in the string.
# Note, you may want to check to ensure that A and B are the same lengths. 
while i<len(A):
    # if the current characters of A and B are the same advance the match incrementor
    if B[i] == A[I]:

        # This is the important change. In your code this line 
        # is outside the if statement, so it advances for every 
        # character that is checked not every character that passes.
        match = match + 1
    
    # Move to the next character
    i = i + 1

# Display the output to the user.
print(match, 'positions.')
aor9mmx1

aor9mmx12#

num_matching = 0
a = "Hello"
b = "Yellow"

shortest_string = a if len(a) <= len(b) else b
longest_string = b if shortest_string == a else a

for idx, val in enumerate(shortest_string):
    if val == b[idx]:
        num_matching += 1
print(f"In {a} & {b} there are {num_matching} characters in the same position!")
o2rvlv0m

o2rvlv0m3#

根据@gog对zipzip_longest的看法,我的答案可以简化:

string1 = "soon"
string2 = "moon"

matching_positions = 0
for c1, c2 in zip(string1, string2):
    if c1 == c2:
        matching_positions += 1
print(matching_positions)

输出:

3

相关问题