当前位置:  首页>> 技术小册>> Python合辑4-130个字符串操作示例

比较两个字符串中的单个字符

  1. def compare_strings(a, b):
  2. result = True
  3. if len(a) != len(b):
  4. print('string lengths do not match!')
  5. for i, (x, y) in enumerate(zip(a, b)):
  6. if x != y:
  7. print(f'char miss-match {x, y} in element {i}')
  8. result = False
  9. if result:
  10. print('strings match!')
  11. return result
  12. print(compare_strings("canada", "japan"))

Output:

  1. string lengths do not match!
  2. char miss-match ('c', 'j') in element 0
  3. char miss-match ('n', 'p') in element 2
  4. char miss-match ('d', 'n') in element 4
  5. False

该分类下的相关小册推荐: