Python string handling: Reversing by word __python

Source: Internet
Author: User

In

Python string processing learning, there is a simple but classic topic that reverses a string by a word and preserves the original space:
such as: ' I love china! '
converted to: ' china! love I '
Two solutions:
Scenario 1: The string is traversed from the time of the trip, if the first is a space, skip directly until the first character is not a space, if it is a separate letter, the same skip, otherwise, the word will be reversed, Iterate back and finally use the Reserve method to print the entire string from the back forward.
Scenario 2: Invert directly using the RE (regularization) package
code as follows:

import re def reserve (Str_list, start, end): While start <= End:str_list[start],   Str_list[end] = Str_list[end], Str_list[start] End-= 1 start = 1 str = ' I love china! ' Str_list = list (str) print (str_list) i = 0 print (len (str_list)) # in the back of the list, if you hit a space, call the inverse function, regardless of a single character case while I < Len (  Str_list): If Str_list[i]!= ': start = I end = start + 1 print (end) while (end < Len (Str_list)) and (str_list[end]!= '): End + 1 if End-start > 1:reserve (str_list , start, end-1) i = end else:i = End Else:i + + 1 print (str_list) STR_LIST.R
Everse () print ('. Join (Str_list)) # using regular expression Operations Str_re = Re.split (R ' (\s+) ', str) str_re.reverse () Str_re = '. Join (Str_re) Print (str_re) 
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.