Home>Article>Backend Development> How to determine if a string is a palindrome in Python?

How to determine if a string is a palindrome in Python?

coldplay.xixi
coldplay.xixi Original
2020-06-15 09:30:16 13852browse

How to determine if a string is a palindrome in Python?

#How to determine whether a string is a palindrome in Python?

Python method to determine whether a string is a palindrome:

1. Palindrome string: a string, whether from left to right, Still from right to left, the order of characters is the same (such as abba, abcba, etc.).

2. How to judge:

It is relatively simple to judge a palindrome string, that is, use two variables left and right to imitate pointers (one points to the first character and one points to the last character). Each time the comparison is successful, left moves one position to the right and right moves one position to the left. If the elements pointed to by left and right are not equal, exit. Finally, compare the sizes of left and right. If left>right, it means it is a palindrome. String.

3. Code

# coding:utf-8; s = input() left = 0 right = len(s) - 1 while left <= right: if s[left] == s[right]: left += 1 right -= 1 else: break if left > right: # print('{}是回文字符串!!!'.format(s)) print("%s是回文字符串" % s) else: # print('{}不是回文字符串!!!'.format(s)) print("%s是回文字符串" % s)

Recommended tutorial: "python video tutorial"

The above is the detailed content of How to determine if a string is a palindrome in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn