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

检查给定的字符串是否是 Python 中的回文字符串

  1. import re
  2. Continue = 1
  3. Quit = 2
  4. def main():
  5. choice = 0
  6. while choice != Quit:
  7. # Display the menu.
  8. display_menu()
  9. # Constant to assume string is Palindrome
  10. is_palindrome = True
  11. # Get the user's choice.
  12. choice = int(input('\nEnter your choice: '))
  13. # Perform the selected action.
  14. if choice == Continue:
  15. line = input("\nEnter a string: ")
  16. str_lower = re.sub("[^a-z0-9]", "", line.lower())
  17. for i in range(0, len(str_lower)//2):
  18. if str_lower[i] != str_lower[len(str_lower) - i - 1]:
  19. is_palindrome = False
  20. if is_palindrome:
  21. print(line, "is a palindrome")
  22. else:
  23. print(line, "is not a palindrome")
  24. else:
  25. print('Thank You.')
  26. def display_menu():
  27. print('\n*******MENU*******')
  28. print('1) Continue')
  29. print('2) Quit')
  30. main()

Output:

  1. *******MENU*******
  2. 1) Continue
  3. 2) Quit
  4. Enter your choice: 1
  5. Enter a string: A dog! A panic in a pagoda!
  6. A dog! A panic in a pagoda! is a palindrome
  7. *******MENU*******
  8. 1) Continue
  9. 2) Quit
  10. Enter your choice: 1
  11. Enter a string: Civic
  12. Civic is a palindrome
  13. *******MENU*******
  14. 1) Continue
  15. 2) Quit
  16. Enter your choice: 1
  17. Enter a string: Python vs Java
  18. Python vs Java is not a palindrome
  19. *******MENU*******
  20. 1) Continue
  21. 2) Quit
  22. Enter your choice: 2
  23. Thank You.

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