Python程序:检查给定字符串是否为回文

创新互联Python教程:

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名虚拟主机、营销软件、网站建设、织金网站维护、网站推广。

用一个实例写一个 Python 程序来检查给定的字符串是不是回文。在 Python 中,如果一个字符串在反转后保持不变,它可以是回文字符串。

检查给定字符串是否回文的 Python 程序示例 1

这个 python 回文字符串程序允许用户输入一个字符串。接下来,我们使用 If 语句来检查给定的字符串是否等于该字符串的反义词。如果是真,回文字符串;否则,不是 Python 中的回文字符串。

字符串[:–1]以相反的顺序返回字符串。请参考弦文章了解蟒弦的一切。

# Python Program to Check a Given String is Palindrome or Not

string = input("Please enter your own String : ")

if(string == string[:: - 1]):
   print("This is a Palindrome String")
else:
   print("This is Not a Palindrome String")

寻找给定字符串的 Python 程序是回文示例 2

在这个 python 程序中,我们使用 For Loop 来迭代字符串中的每个字符。在 For 循环中,我们将每个字符分配给 str1(之前)。接下来,我们使用 If 语句检查 python 中的回文字符串。

string = input("Please enter your own String : ")
str1 = ""

for i in string:
    str1 = i + str1  
print("String in reverse Order :  ", str1)

if(string == str1):
   print("This is a Palindrome String")
else:
   print("This is Not a Palindrome String")

Python 回文串输出

Please enter your own String : aabbcc
String in reverse Order :   ccbbaa
This is Not a Palindrome String
>>> 
Please enter your own String : aabbaa
String in reverse Order :   aabbaa
This is a Palindrome String
>>> 

检查字符串是否回文的 Python 程序示例 3

在这个 Python 回文字符串程序中,我们是用 len 函数来求字符串长度的。接下来,我们使用递归函数递归调用该函数。

def reverse(str1):
    if(len(str1) == 0):
        return str1
    else:
        return reverse(str1[1 : ]) + str1[0]

string = input("Please enter your own String : ")
str1 = reverse(string)
print("String in reverse Order :  ", str1)

if(string == str1):
   print("This is a Palindrome String")
else:
   print("This is Not a Palindrome String")

Python 回文字符串输出

Please enter your own String : wow
This is a Palindrome String
>>> 
Please enter your own String : python
This is Not a Palindrome String
>>> 

Python 回文字符串程序示例 4

在 Python 中,找到给定的字符串是否是回文字符串是一种更传统或更古老的方法。

string = input("Please enter your own String : ")
flag = 0

length = len(string)
for i in range(length):
    if(string[i] != string[length - i - 1]):
        flag = 1
        break

if(flag == 0):
   print("This is a Palindrome String")
else:
   print("This is Not a Palindrome String")
Please enter your own String : aabbcbbaa
This is a Palindrome String
>>> 
Please enter your own String : tutorialgateway
This is Not a Palindrome String
>>>

当前标题:Python程序:检查给定字符串是否为回文
本文来源:http://www.hantingmc.com/qtweb/news2/510152.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联