Python string-by-character or word-wise reversal method

Source: Internet
Author: User
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)))

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.