To play a Python string character-by-byte or word-wise reversal

Source: Internet
Author: User

It is well known that the string in Python cannot be changed, and the inverse of a string naturally creates a copy; The simple method of mouth is, of course, a slice of "-1" in step:

result = Astring[::-1]

If you invert by word, you need three steps: string---> Word list, reverse list, word list---> string;

1 result = astring.split ()2result.reverse ()    3" . Join (Result)

If you prefer a concise and compact line of code, you can do this:result = '. Join (Astring.split () [:: -1])

But [::-1] reduces readability, but it can also be written like this:result = '. Join (Reversed (Astring.split ()))

Suppose the case: while working with the string, it is guaranteed not to change the number of spaces, and it is obvious that the above method does not work, which is when the regular expression comes out:

1 Import Re 2 result = Re.split (r'(\s+)', astring)3result.reverse ()  4'. Join (Result)        # Note ' There's no space in the middle ' Oh

The same line can accomplish this task:result = '. Join (Re.split (R ' (\s+) ', astring) [:: -1])

summary: Unfortunately, this article at the beginning of the writing is better than this, but because of the accidental loss of unfinished draft, but the inspiration is not all, Do your best to write it like this;

Related Article

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.