Python reverse list

I'm trying to reverse a string and using the below code but the resultant reverse list value is None.

The code:

str_a = 'This is stirng'
rev_word = str_a.split()
rev_word = rev_word.reverse()
rev_word = ''.join(rev_word)

It returns the TypeError. Why?


This is my personal favorite way to reverse a string:

stra="This is a string"
revword = stra[::-1]

print(revword) #"gnirts a si sihT

or, if you want to reverse the word order:

revword = " ".join(stra.split()[::-1])

print(revword) #"string a is This"

:)


.reverse() returns None. Therefore you should not be assigning it to a variable.

Use this instead:

stra = 'This is a string'
revword = stra.split()
revword.reverse()
revword=''.join(revword)

I've run the code on IDEOne for you so you can see the output. (Also notice that the output is stringaisThis; you may want to use ' '.join(revword), with a space, instead.)

Also note that the method you have provided only reverses the words, not the text. @ron.rothman provided a link that does detail how to reverse a string in its entirety.


Various reversals on a string:

instring = 'This is a string'
reversedstring = instring[::-1]
print reversedstring        # gnirts a si sihT
wordsreversed = ' '.join(word[::-1] for word in instring.split())
print wordsreversed         # sihT si a gnirts
revwordorder = ' '.join(word for word in instring.split()[::-1])
print revwordorder          # string a is This
revwordandorder = ' '.join(word[::-1] for word in instring.split()[::-1])
print revwordandorder       # gnirts a si sihT

For future reference when an object has a method like [].reverse() it generally performs that action o n the object (ie. the list is sorted and returns nothing, None) in contrast to built in functions like sorted which perform an action on an object and returns a value (ie the sorted list)