This article mainly introduces the Python string literal character or the word reversal method, this article has given two kinds of methods to the literal character or the individual word, the need friend may refer to the next
Objective
It's interesting to reverse the string literal character or Word by line.
Method
First look at the character reversal, the first set the slice size to 1
The code is as follows:
REVCHARS=ASTRING[::-1]
In [$]: x= ' ABCD '
In [$]: x[::-1]
OUT[66]: ' DCBA '
The second approach is to use reversed (), noting that it returns an iterator that can be used to loop or pass to other "accumulators", not a completed string.
The code is as follows:
Revchars= '. Join (Reversed (astring))
In [to]: y=reversed (x)
in [+]: Y
OUT[57]:
In [Gen]: '. Join (Y)
OUT[58]: ' DCBA '
Then look at the word reversal.
The first approach is to create a list that reverses the list and merges it with the Join method
The code is as follows:
In [PDF]: s= ' is really a good day '
in [[]: Rev=s.split ()
in [): Rev
OUT[40]: [' Today ', ' are ', ' really ', ' a ', ' good ', ' Day ']
In [$]: Rev.reverse ()
In [a]: Rev
OUT[42]: [' Day ', ' good ', ' a ', ' really ', ' are ', ' today ']
in [[]: '. Join (REV)
OUT[45]: ' Day good a really are today '
There is also a line of code to resolve:
The code is as follows:
Rev= '. Join (S.split () [::-1])
The second approach is to do so without changing the original space and using a regular formula:
The code is as follows:
in [+]: Import re
In [$]: Rev=re.split (R ' (s+) ', s)
in [+]: Rev
OUT[48]: [' Today ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ', ' good ', ']
in [[]: Rev.reverse ()
In [m]: Rev
OUT[50]: [' Day ', ', ' good ', ', ' a ', ', ', ' really ', ', ', ', ', ', ', ', ', '
In [Wuyi]: rev= '. Join (REV)
In [i]: rev
OUT[52]: ' Day good a really are today '
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))