Python string processing implements word inversion, python string

Source: Internet
Author: User

Python string processing implements word inversion, python string

In Python string processing, there is a simple but classic question. The string is reversed by word and the original space is retained:
For example, 'I love China! '
Converted to: 'China! Love I'

Two solutions:

Solution 1: traverse the string from the beginning to the end. If the first character is a space, skip it directly until the first character is not a space. If it is a separate letter, skip it. Otherwise, reverse the word, traverse it later, and use the reserve method to print the entire string from the back to the back.

Solution 2: reverse using the re (Regularization) package directly

The Code is as follows:

Import redef reserve (str_list, start, end): while start <= end: str_list [start], str_list [end] = str_list [end], str_list [start] end-= 1 start + = 1str = 'I love china! 'Str _ list = list (str) print (str_list) I = 0 print (len (str_list) # traverse the list from the past to the next. If there is a space, call the reverse function, ignore a single character 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 + = 1 print (str_list) str_list.reverse () print (''. join (str_list) # use a regular expression to operate str_re = re. split (R' (\ s +) ', str) str_re.reverse () str_re = ''. join (str_re) print (str_re)

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.