What is palindrome string?
什么是回文字符串?
A string is a palindrome if the string read from left to right is equal to the string read from right to left i.e. if the actual string is equal to the reversed string.
如果從左至右讀取的字符串等于從右至左讀取的字符串,即實際字符串等于反向字符串,則該字符串為回文 。
In the below program, we are implementing a python program to check whether a string is a palindrome or not?
在下面的程序中,我們正在實現一個python程序來檢查字符串是否是回文?
Steps:
腳步:
First, find the reverse string
首先,找到反向字符串
Compare whether revers string is equal to the actual string
比較反轉字符串是否等于實際字符串
If both are the same, then the string is a palindrome, otherwise, the string is not a palindrome.
如果兩者相同,則該字符串是回文,否則,該字符串不是回文。
Example:
例:
Input:
"Google"
Output:
"Google" is not a palindrome string
Input:
"RADAR"
Output:
"RADAR" is a palindrome string
Method 1: Manual
方法1:手動
# Python program to check if a string is
# palindrome or not
# function to check palindrome string
def isPalindrome(string):
result = True
str_len = len(string)
half_len= int(str_len/2)
for i in range(0, half_len):
# you need to check only half of the string
if string[i] != string[str_len-i-1]:
result = False
break
return result
# Main code
x = "Google"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
x = "ABCDCBA"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
x = "RADAR"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
Output
輸出量
Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string
Method 2: Slicing
方法2:切片
# Python program to check if a string is
# palindrome or not
# function to check palindrome string
def isPalindrome(string):
rev_string = string[::-1]
return string == rev_string
# Main code
x = "Google"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
x = "ABCDCBA"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
x = "RADAR"
if isPalindrome(x):
print(x,"is a palindrome string")
else:
print(x,"is not a palindrome string")
Output
輸出量
Google is not a palindrome string
ABCDCBA is a palindrome string
RADAR is a palindrome string
翻譯自: https://www.includehelp.com/python/program-to-check-if-a-string-is-palindrome-or-not.aspx