- 1
Palindrome
Need help to understand something. When i write a code that identifies if the word is pelidrome or not. word = input("please chose a word:") rvrs_word = reversed(word) print(rvrs_word) This does not print the actuall reversed word. As sid in the tutorial strings are also lists.... Sooooo why cant i basically reverse and print it ,if its a list? Why do i have to put a list command....
10 Answers
+ 1
Okay, I told you nonsense above there, sorry!
reversed(word) returns an iterator, not a list, so you indeed have to turn it into the list if you want a list. Or, as I wrote, turn it into a string with join.
What do you need all these lists for anyway? Can you describe a bit, what your program is supposed to do?
+ 5
Strings are different from lists: They can't be changed, their shape is fixed.
So what reversed does is this: It copies every letter from your string and puts the letters in reversed order into a list.
What you have to do: Connect these letters to a new string. Luckily that's not too hard:
''.join(reversed(word))
Even easier would be to just put a reversed copy of your string into the variable directly.
rvrs_word = word[::-1]
+ 1
reversed(word) leads to a list, so list(reversed(word)) is useless because it turns a list again into a list. You want a string instead, so you use the string's method 'join'.
Demonstration:
'-'.join('123') - - > '1-2-3'
'>'.join(['a', 'b', 'c']) - - > 'a>b>c'
''. join(['h', 'i']) - - > 'hi'
+ 1
In your code I see no attempt yet to apply any of the patterns I just taught you.
Come on, try - you can do it!
0
.join
or
rvrs_word = list(reversed(word))
Is basically the same?
And how exactly do i use the .join.
Thank you very much! Btw
0
https://code.sololearn.com/c6gDWMMl0OUW/?ref=app
Id be glad if you could help
0
I cant seem to understand. When run my code, the end result wont print the string aka list of letters in reverse. It just says [<reversedobject ect.......
Thats the only thing thats holding me back. Other than that, everything is understood.
Only when i put list command before the reverse(word)
It does print it as list contaning letters in reverse.
but!
Puts it as list inside a list.
0
I hope i made myself clear.....
0
I basically want to write a program that tells the user if the word he wrote is a plindrome.
If its a plindrome it should print correct.
This is why i need to compare a string to a reverse string.
If not poli it should print wrong and the reversed string .
0
Okay, you only want to compare two strings basically. Why do you even want to store the reversed string in a list?