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

在 Python 中遍历字符串

  1. # Example 1
  2. test_str = "Canada"
  3. for i, c in enumerate(test_str):
  4. print(i, c)
  5. print("------------------------")
  6. # Example 2
  7. indx = 0
  8. while indx < len(test_str):
  9. print(indx, test_str[indx])
  10. indx += 1
  11. print("------------------------")
  12. # Example 3
  13. for char in test_str:
  14. print(char)

Output:

  1. 0 C
  2. 1 a
  3. 2 n
  4. .......
  5. d
  6. a