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?

2
  • 6
    Already answered here? (Personally, I like the ''.join(reversed(s)) solution there.) Commented Sep 9, 2012 at 2:46
  • 1
    I wish #reverse returned a reference to self. I guess Guido van Rossum was not as into method chaining as Yukihiro Matsumoto. Commented May 12, 2014 at 1:00

8 Answers 8

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"

:)

3
  • 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. Commented Jun 12, 2013 at 13:34
  • @thefourtheye see this stackoverflow: stackoverflow.com/questions/509211/the-python-slice-notation Commented Jun 12, 2013 at 23:57
  • @SeanJohnson So, if we give -1 as the step value, by default it will traverse backwards. Is that right? Commented Jun 13, 2013 at 1: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.

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
0
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)

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'
2
  • 2
    Consider providing some explanation!
    – Konsole
    Commented May 8, 2014 at 8: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
    Commented May 8, 2014 at 8: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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.