This article mainly introduces the character-by-character or word-by-word inversion methods of Python strings. This article provides two methods for character-by-character or word-by-word conversion. For more information, see
Purpose
It is interesting to reverse a string by character or word.
Method
Let's first look at the character-by-character inversion. The first method is to set the slice step to-1.
The Code is as follows:
Revchars = astring [:-1]
In [65]: x = 'abc'
In [66]: x [:-1]
Out [66]: 'dcba'
The second approach is to use reversed (). Note that it returns an iterator that can be used to loop or pass to other "accumulators" instead of a completed string.
The Code is as follows:
Revchars = ''. join (reversed (astring ))
In [56]: y = reversed (x)
In [57]: y
Out [57]:
In [58]: ''. join (y)
Out [58]: 'dcba'
Next, let's look at word-by-word reversal.
First, create a list, reverse the list, and merge the list using the join method.
The Code is as follows:
In [38]: s = 'Today is really a good day'
In [39]: rev = s. split ()
In [40]: rev
Out [40]: ['today', 'is ', 'Really', 'A', 'good ', 'day']
In [41]: rev. reverse ()
In [42]: rev
Out [42]: ['day', 'good', 'A', 'Really ', 'is', 'today']
In [45]: ''. join (rev)
Out [45]: 'Day good a really is today'
There is also a line of code to solve the problem:
The Code is as follows:
Rev = ''. join (s. split () [:-1])
The second method does not change the original space. The regular expression is used to do the following:
The Code is as follows:
In [46]: import re
In [47]: rev = re. split (R' (\ s +) ', s)
In [48]: rev
Out [48]: ['today', '', 'is ','', 'Really', '', 'A','', 'good ', '', 'day']
In [49]: rev. reverse ()
In [50]: rev
Out [50]: ['day', '', 'good','', 'A', '', 'Really ','', 'is ', '', 'today']
In [51]: rev = ''. join (rev)
In [52]: rev
Out [52]: 'Day good a really is today'
You can consider using reversed () instead of the less readable [:-1]
The Code is as follows:
Revwords = ''. join (reversed (s. split ()))
Revwords = ''. join (reversed (re. split (R' (\ s +) ', s )))