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)