如何比较字符串的两个元素?python

如何比较字符串的两个元素?python,python,Python,我需要比较用户输入的两个字符串。然后我需要检查第一个字符串中的每个字符与第二个字符串中的相同字符位置,如果它们匹配,我需要在“分数”中添加1,如果它们不匹配,我需要跳出循环。任何提示都会非常有用。谢谢 然后我需要检查第一个字符串中的每个字符是否具有相同的 字符在第二个字符串中的位置,如果它们匹配,我需要添加 1比1“得分” 您可以使用以下内容: score = 0 while 1: str1 = input("Type 1st string:") str2 = inp

我需要比较用户输入的两个字符串。然后我需要检查第一个字符串中的每个字符与第二个字符串中的相同字符位置,如果它们匹配,我需要在“分数”中添加1,如果它们不匹配,我需要跳出循环。任何提示都会非常有用。谢谢

然后我需要检查第一个字符串中的每个字符是否具有相同的 字符在第二个字符串中的位置,如果它们匹配,我需要添加 1比1“得分”

您可以使用以下内容:

score = 0
while 1:
  str1 = input("Type 1st string:")
  str2 = input("Type 2nd string:")
  
  if str1 == str2:
    score += 1
    print("Strings are equal")
    print("Score: ", score)
  else:
    print("Strings are different")
    print("Score: ", score)
    
  cont = input("Continue ?\n'y' to continue any other key to quit.")
  if cont.lower() != "y":
    break

print("Final score:", score)


我们一步一步走吧。从用户获取2个字符串作为输入:

firstString=input()
secondString=input()
打印(第一个字符串,第二个字符串)
很好。现在让我们对它们进行迭代,看看会发生什么

firstString=input()
secondString=input()
lastIndex=min(len(第一个字符串),len(第二个字符串))
对于范围内的i(lastIndex):
打印(第一个字符串[i],第二个字符串[i])
酷。我们从每个字符串打印索引i处的字符,而这两个字符串中都有字符。现在剩下要做的就是计算你的分数

firstString=input()
secondString=input()
lastIndex=min(len(第一个字符串),len(第二个字符串))
分数=0
对于范围内的i(lastIndex):
如果firstString[i]==secondString[i]:
分数+=1
其他:
打破
打印(分数)

这应该行得通。我没试过

如果str1==str2:
…欢迎使用堆栈溢出!请拿着这本书,读一读,效果很好,非常感谢。出于某种原因,我试图在for循环中使用嵌套的while循环,而不仅仅是if语句。
# Accept two strings from user
a = input("Enter 1st string:")
b = input("Enter 2nd string:")

# Get the minimum of lengths of both the strings
min_len = min(len(a), len(b))

# Set the counter variable to 0
score = 0

# Loop till the minimum length. Eg: if min_len is 4, you will loop the values 0,1,2,3
for i in range(min_len):

  # Compare each character, if match then increase score
  if a[i] == b[i]:
     score = score + 1
  # Else break out of loop
  else:
     break

print(score)