所以我最近實現了一個代碼來檢查一個單詞是否是迴文。改善Python迴文代碼
def isPalindrome():
string = input('Enter a string: ')
string1 = string[::-1]
if string[0] == string[(len(string)-1)] and string[1:(len(string)-2)] == string1[1:(len(string)-2)]:
print('It is a palindrome')
else:
print('It is not a palindrome')
isPalindrome()
我想知道是否有人可以給我提示簡化代碼。
編輯 - 如果我要使用語句string == string1
作爲迭代函數,我將如何停止無盡的while循環?我需要一個計數來停止while循環嗎?
你覺得'string [:: - 1]'是做什麼的? –
對於像這樣的問題(**工作代碼**在需要審查),http://codereview.stackexchange.com/是一個很好的地方。堆棧溢出是真的意味着代碼不起作用的問題 –
@steve所以你知道,讓你反向的字符串。那你爲什麼需要'if-else'條件?你已經得到了原始的字符串,你已經得到了該字符串的反轉。只是比較它們。 –