Home > Backend Development > Python Tutorial > A Byte of Python - Palindrome

A Byte of Python - Palindrome

巴扎黑
Release: 2016-12-08 10:53:57
Original
1866 people have browsed it

A palindrome is a string that is the same when read forward or backward.
Create the file palindrome.py and enter the following code:

#设置需要过虑的标点符号
forbidden = (".", "?", "!", ":", ";", "-", "—", "()", "[]", "...", "'", '""', "/", ",", " ")
#获取一个字符串,书中要求确认"Rise to vote, sir."是回文
text = input("请输入:")
#将字符串倒过来
def reverse(text):
str_tmp = []
str = ""
for i in range(0,len(text)):
if text[i] in forbidden:
continue
else:
str_tmp.append(text[i].lower())#方便比较,将字母转成小写字母
return str.join(str_tmp)[::-1]
#做是否是回文检测
def is_palindrome(text):
str_tmp = []
str = ""
for i in range(0,len(text)):
if text[i] in forbidden:
continue
else:
str_tmp.append(text[i].lower())
return str.join(str_tmp) == reverse(text)
#输出检测结果
if is_palindrome(text):
print(text, "是回文")
else:
print(text, "不是回文")
Copy after login


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