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.