Python中的回文

时间:2012-05-05 10:18:30

标签: python if-statement for-loop palindrome

fno = input()
myList = list(fno)
sum = 0
for i in range(len(fno)):
    if myList[0:] == myList[:0]:
    continue
print (myList)

我想做一个数字回文。 例如:

input(123)
print(You are wrong)
input(12121)
print(you are right) 

请指导我如何在python中制作回文。如果没有完整的代码请告诉我下一步是什么。

由于

4 个答案:

答案 0 :(得分:6)

我认为,鉴于你的代码,你想要检查一个回文,而不是一个。

您的代码存在许多问题,但简而言之,它可以缩减为

word = input()
if word == "".join(reversed(word)):
    print("Palidrome")

让我们谈谈您的代码,这没有多大意义:

fno = input() 
myList = list(fno) #fno will be a string, which is already a sequence, there is no need to make a list.
sum = 0 #This goes unused. What is it for?
for i in range(len(fno)): #You should never loop over a range of a length, just loop over the object itself.
    if myList[0:] == myList[:0]: #This checks if the slice from beginning to the end is equal to the slice from the beginning to the beginning (nothing) - this will only be true for an empty string.
        continue #And then it does nothing anyway. (I am presuming this was meant to be indented)
print (myList) #This will print the list of the characters from the string.

答案 1 :(得分:5)

切片符号在这里很有用:

>>> "malayalam"[::-1]
'malayalam'
>>> "hello"[::-1]
'olleh'

请参阅Explain Python's slice notation以获得详细介绍。

答案 2 :(得分:0)

str=input('Enter a String')
print('Original string is : ',str)
rev=str[::-1]
print('the reversed string is : ',rev)
if(str==rev):
    print('its palindrome')
else:
    print('its not palindrome')

答案 3 :(得分:-1)

x=raw_input("enter the string")
while True:
    if x[0: ]==x[::-1]:
        print 'string is palindrome'
        break
    else:
        print 'string is not palindrome'
        break