Python string processing implements word inversion

  • 2020-06-03 07:13:08
  • OfStack

In Python string processing study, there is a simple but classic question, which reverses the string according to the word and retains the original space:
'I love China! '
Translate to: 'China! love I '

Two solutions:

Scenario 1: Iterate over the string from front to back. If the first character is a space, skip it until the first character is not a space. If it is a single letter, skip it again.

Scenario 2: Reverse directly using the re(regularized) package

The code is 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))

#  Go back and forth list If a space is encountered, the reverse function is called, regardless of 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 = end
  else:
    i += 1

print(str_list)
str_list.reverse()
print(''.join(str_list))

#  Use regular expression operations 
str_re = re.split(r'(\s+)',str)

str_re.reverse()
str_re = ''.join(str_re)
print(str_re)

Related articles: