简体   繁体   中英

Why my reverse() method doesn't work in python 3?

I was trying to do this exercise where you have to take a word and check if it's a palindrome. I tried to do it with making a string in to a list then reversing it and turning it back to a string, but the reverse method doesn't work for me for some reason, I checked and the usage is correct.

word = input('Give me a word:\n')
b = []
wordLetters = word.split()
b = wordLetters.reverse()
word2 = ''.join(b)

if word == word2:
    print('Yay')
else:
    print('heck')

it just shows

TypeError: can only join an iterable

list()的reverse()方法不返回任何内容,但会在Python 3中本身反转列表。因此,请加入wordLetters而不是b。希望这可以解决问题。

In Python reverse method of list does the operation in-place eg it modifies the list you apply this operation to. This method has no return value.

l = [1, 2, 3, 4]
l.reverse()
print(l)

Output:

[4, 3, 2, 1]

If you try to get value returned by reverse you will get None :

print([1, 2, 3, 4].reverse())

Output:

None

If you need a reversed copy of your list you should use reversed function:

l = [1, 2, 3, 4]
r = reversed(l)
print(r)
print(list(r))

Output:

<list_reverseiterator object at 0x7ff37e288ef0>
[4, 3, 2, 1]

Notice that it returns iterator, not the list itself. You can pass that iterator to join function or you can build a list from it using list constructor.

The same is true for method sort and function sorted .

As the documentation states:

list.reverse()

Reverse the elements of the list in place.

That means this method won't return anything (otherwise it would state what it returns) and that it reverses the list in-place.

Also str.split will (by default) split at whitespaces which is probably not intended from the problem description.

My suggestion would be to simply use slice notation for reversing the string:

word = input('Enter your word')
if word == word[::-1]:
    print('Yay')
else:
    print('heck')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM