python中怎么判断一个单词是不是回文_如何检查单词是否为回文(Python)

你可以先把这个列表转换成一个字符串,然后再把它转换成一个字符串。比较两个字符串是否匹配?它们是回文,如果不是,它们就不是'''checking whether a word is a palindrome

we first convert the word into a list then join it;

use an if statement to compare the two strings'''

def palindrome(string):#you need the input(string)

palindrome_check=[]#create an empty list

for character in string [::-1]:#create a list from the input

#(use a for loop because you now know the range)

#the [::-1] analyzes the characters in reverse

palindrome_check.append(character)#add each character to the new empty list

#print(palindrome_check)

rev_string= ''.join(palindrome_check)#.join -creates a string from the created list

print(rev_string)

#REMOVE SPECIAL CHARACTERS- IM THINKING OF A LOOPING THROUGH, BUT NOT SURE HOW TO IMPLEMENT IT

string=string.replace(' ', '')

rev_string=rev_string.replace(' ', '')

string=string.replace(',', '')

rev_string=rev_string.replace(',', '')

string=string.replace('.', '')

rev_string=rev_string.replace('.', '')

#THIS IS THE LOGIC: IT CHECKS BOTH STRINGS, if they are equal, it is a palindrome;

if string.lower()==rev_string.lower():

return True, print('It is a Palindrome')

else:

return False, print('It isnt a palindrome')

#call the function; key in the parameters-

palindrome= palindrome("No, Mel Gibson Is A Casinos Big Lemon")

#maybe we can try having a user key in the parameter? lets try

#palindrome=palindrome(input('kindly enter your word/phrase '))-wrong

#print('Kindly enter your word or phrase')

#user_palindrome=input('')

#palindrome=palindrome(user_palindrome)

#it wont work this way either

如果你能让用户定义参数(字符串),那就更好了,如果你知道怎么做,请分享。在

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值