Hello I am mainly a JavaScript developer learning some Python and I was doing the isPalindrome algorithm
I wrote this in JS
function isPalindrome(string) {
const reverseStr = string.split('').reverse().join('');
return string === reverseStr;
}
console.log(isPalindrome('abcdcba'))
But I had a hard time replicating this logic in python
Here is what i have so far
def isPalindrome(string):
reverseStr = list(string)
reverseStr.reverse()
print(reverseStr)
# return string == reverseStr
print(isPalindrome('abcdcba'))
How can I chain methods in Python like JavaScript? Thanks
CodePudding user response:
After reverse the list of chars you need to rejoin using join
method of strings in Python, so
def isPalindrome(string):
reverseStr = list(string)
reverseStr.reverse()
return string == ''.join(reverseStr)
It works, but the easier way to check for palindromes as highlighted by porrrwal is string == string[::-1]
CodePudding user response:
This is very simple to do in python. Try this:
string == string[::-1]
So for your function you can just use:
def isPalindrome(string):
return string == string[::-1]