Purpose
It's interesting to reverse the string literal character or word by phrase.
Method
Look at the character reversal first, the first set the step size of the slice is-1
Copy the Code code as follows:
REVCHARS=ASTRING[::-1]
in [+]: x= ' ABCD '
In [all]: X[::-1]
OUT[66]: ' DCBA '
The second approach is to use reversed (), noting that it returns an iterator that can be used for looping or passing to other "accumulators", not a completed string.
Copy the Code code as follows:
Revchars= '. Join (Reversed (astring))
In []: y=reversed (x)
In [the]: Y
OUT[57]:
in [+]: '. Join (Y)
OUT[58]: ' DCBA '
Then look at the word reversal.
The first approach, create a list, reverse the list, merge with the Join method
Copy the Code code as follows:
in [+]: s= ' Today is really a good day '
In [All]: Rev=s.split ()
In [MAX]: Rev
OUT[40]: [' Today ', ' is ', ' really ', ' a ', ' good ', ' Day ']
in [+]: Rev.reverse ()
In [all]: Rev
OUT[42]: [' Day ', ' good ', ' a ', ' really ', ' is ', ' Today ']
in []: ". Join (REV)
OUT[45]: ' Day good a really is Today '
There is also a line of code to resolve:
Copy the Code code as follows:
Rev= '. Join (S.split () [::-1])
The second approach can be done without changing the original space and using the regular formula:
Copy the Code code as follows:
in [+]: Import re
In [Sat]: Rev=re.split (R ' (\s+) ', s)
in [+]: Rev
OUT[48]: [' Today ', ' ', ' is ', ' ', ' really ', ' ', ' a ', ', ' good ', ' ', ' Day ']
in [+]: Rev.reverse ()
in [+]: Rev
OUT[50]: [' Day ', ' ', ' good ', ' ', ' a ', ' ', ' really ', ', ' is ', ', ' Today ']
In [Wuyi]: rev= '. Join (REV)
In [%]: Rev
OUT[52]: ' Day good a really is Today '
Consider using reversed () instead of poor readability [::-1]
Copy the Code code as follows:
Revwords= '. Join (Reversed (S.split ()))
Revwords= '. Join (Reversed (Re.split (R ' (\s+) ', s)))