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

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

coldplay.xixi
Release: 2020-06-15 09:30:16
Original
13984 people have browsed it

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(&#39;{}是回文字符串!!!&#39;.format(s))
    print("%s是回文字符串" % s)
else:
    # print(&#39;{}不是回文字符串!!!&#39;.format(s))
    print("%s是回文字符串" % s)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template