50

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?

vaultah
  • 44,105
  • 12
  • 114
  • 143
user1050619
  • 19,822
  • 85
  • 237
  • 413
  • 6
    Already [answered](http://stackoverflow.com/questions/931092/reverse-a-string-in-python) here? (Personally, I like the ''.join(reversed(s)) solution there.) – ron rothman Sep 09 '12 at 02:46
  • 1
    I wish `#reverse` returned a reference to `self`. I guess Guido van Rossum was not as into method chaining as Yukihiro Matsumoto. – Eric Walker May 12 '14 at 01:00

8 Answers8

123

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"

:)

Sean Johnson
  • 5,567
  • 2
  • 17
  • 22
  • I know it works. But I was expecting "T", as we havnt mentioned anything for the start and end, I expected Python to start with 0 and move backwards. Please let me know how it works. – thefourtheye Jun 12 '13 at 13:34
  • @thefourtheye see this stackoverflow: http://stackoverflow.com/questions/509211/the-python-slice-notation – Sean Johnson Jun 12 '13 at 23:57
  • @SeanJohnson So, if we give -1 as the step value, by default it will traverse backwards. Is that right? – thefourtheye Jun 13 '13 at 01:07
53

.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.

Mr Mystery Guest
  • 1,464
  • 1
  • 18
  • 47
Cat
  • 66,919
  • 24
  • 133
  • 141
7

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
Paddy3118
  • 4,704
  • 27
  • 38
6

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)

dm03514
  • 54,664
  • 18
  • 108
  • 145
4
>>> s = 'this is a string'
>>> s[::-1]
'gnirts a si siht'
>>> ''.join(reversed(s))
'gnirts a si siht'
0

The for loop iterates the string from end (last letter) to start (first letter)

>>> s = 'You can try this too :]'
>>> rev = ''
>>> for i in range(len(s) - 1, -1, -1):
...     rev += s[i]
>>> rev
']: oot siht yrt nac uoY'
Konsole
  • 3,447
  • 3
  • 29
  • 39
Aziz Alto
  • 19,057
  • 5
  • 77
  • 60
  • 2
    Consider providing some explanation! – Konsole May 08 '14 at 08:02
  • rev is an empty string var. The for loop iterates the original string backward, (from the end "last letter" to the beginning "first letter"). In every iteration, the corresponding letter is appended to rev. Let me know if this is helpful :] – Aziz Alto May 08 '14 at 08:42
0

Based on comments and other answers:

str_a = 'this is a string'
rev_word = ' '.join(reversed(str_a.split()))

Method chaining does work in Python after all...

0

List reverse can be done using more than one way.
As mentioned in previous answers two are very prominent, one with reverse() function and two with slicing feature. I'm giving some insights on which one we should prefer. We should always use reverse() function for reversal of a Python list. Two reasons, one in-place reversal and two faster than other. I've some figures to support my answer,

In [15]: len(l)
Out[15]: 1000

In [16]: %timeit -n1 l.reverse()
1 loops, best of 3: 7.87 µs per loop

In [17]: %timeit -n1 l[::-1]
1 loops, best of 3: 10 µs per loop

For 1000 integer list, reverse() function performed better compared to slicing.

Aashish P
  • 1,894
  • 5
  • 22
  • 36