Python64
Posted on March 4, 2020
In this article, we use Python to reverse string character by character or word-by-word.
First we look at the string character by character reversal, because the python provides a very useful sections, so lets see
Reverse characters
You can reverse the characters in a string or a list of strings. The example below shows how to do that:
>>> a = 'abc edf degd'
>>> a [:: -1]
'dged fde cba'
>>>
You can also do this (same, but more clear):
>>> a = 'abcd abcd abcd'
>>> a [:: -1]
'dcba dcba dcba'
>>>
This can also be applied to a list of strings:
>>> a = 'abc abc abc'
>>> a[:: -1].split()
['cba', 'cba', 'cba']
>>>
Reverse word order
The method reverse
may be used to reverse item order. In this example the string a
is converted into a list of strings using the .split()
method. Then the .reverse()
method changes the order of the list.
>>> a = 'AAA BBB CCC'
>>> r = a.split()
>>> r
['AAA', 'BBB', 'CCC']
>>> r.reverse()
>>> r
['CCC', 'BBB', 'AAA']
>>>
The reverse()
method can be applied on any list, so you can also use it for a list of numbers:
>>> a = [ 1,2,3,4,5,6 ]
>>> a.reverse()
>>> a
[6, 5, 4, 3, 2, 1]
>>>
Posted on March 4, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.