Python程序检查字符串是否是回文
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.
如果從左至右讀取的字符串等于從右至左讀取的字符串,即實(shí)際字符串等于反向字符串,則該字符串為回文 。
In the below program, we are implementing a python program to check whether a string is a palindrome or not?
在下面的程序中,我們正在實(shí)現(xiàn)一個(gè)python程序來(lái)檢查字符串是否是回文?
Steps:
腳步:
First, find the reverse string
首先,找到反向字符串
Compare whether revers string is equal to the actual string
比較反轉(zhuǎn)字符串是否等于實(shí)際字符串
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 stringInput:"RADAR"Output:"RADAR" is a palindrome stringMethod 1: Manual
方法1:手動(dòng)
# Python program to check if a string is # palindrome or not# function to check palindrome string def isPalindrome(string):result = Truestr_len = len(string)half_len= int(str_len/2)for i in range(0, half_len):# you need to check only half of the stringif string[i] != string[str_len-i-1]:result = Falsebreakreturn 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 stringMethod 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
總結(jié)
以上是生活随笔為你收集整理的Python程序检查字符串是否是回文的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: c语言中将整数转换成字符串_在C语言中将
- 下一篇: java 嵌套调用_Java嵌套类的使用