I want to make a program that reads whether a sentence is a palindrome or not.
I've already seen what people upload about palindromes in python but I wanted to do it a little differently, however I'm already stuck with the problem because it falls short. I only need to remove the whitespace, but I get the following error:
TypeError: descriptor 'remove' for 'list' objects doesn't apply to a 'str' object
My code is the following:
def palindromo():
p=str(input("Introduce una frase: "))
p_list=list(p)
p_list_rev=list(reversed(p))
for element in p_list:
list.remove(' ',)
print(p_list)
print(p_list_rev)
if p_list==p_list_rev:
print("Es un palindromo")
else:
print("No es un palindromo")
palindromo()
As I said in my comment, the error is that the method
remove
is proper to lists and apart from the fact that you make the error of doinglist.remove
wherelist
it is not defined and it is a reserved word. You don't need to do any looping and with a simple list comprehension you can get rid of the spaces.List comprehension is nothing more than a
for
reduced loop , in which concrete and simple operations are performed , the syntax is:Which means that an operation will be done for each variable, and if there is a condition, the value will only be stored if said condition is met.
for
You can do it with a normal cycle if you don't find it very comfortable.As you may have noticed in the list comprehension there is no
append
where the operation would go and this is because by default they are already added. List comprehensions are very useful and faster thanfor
conventional loops.It is not necessary to do
str(input("..."))
, since itinput(...)
returns a string.You don't need to convert the string to a list; strings and lists are quite similar in Python.
To invert the string,
p
a slice is enough:The slicing has omitted the start and end index, so it covers the entire string. The fun is in the
-1
end, which tells you how to advance through the characters. The value-1
causes the string to loop from the end to the beginning.So, to check if a string
p
is a palindrome, just check the condition.In short, the final code is:
show
We also separate input/output from processing. This gives flexibility when it comes to reusing code. For example, I can test the function without having to enter the texts each time:
produces: