Home  >  Article  >  Backend Development  >  Python implements word reversal effect

Python implements word reversal effect

巴扎黑
巴扎黑Original
2017-08-08 14:49:091887browse

This article mainly introduces in detail the method of word reversal in Python string processing, which has certain reference value. Interested friends can refer to

Python String Processing Learning , there is a simple but classic question, which is to reverse the string according to the words and retain the original spaces:
For example: ' I love China! '
Convert to: ' China! love I '

Two solutions:

Solution 1: Traverse the string from front to back. If the first one is a space, skip it directly , until the first character that is not a space, if it is a separate letter, skip it as well, otherwise, reverse the word, traverse backward, and finally use the reserve method to print the entire string from back to front.

Option 2: Directly use the re (regularization) package for inversion

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 = &#39; I love china!  &#39;
str_list = list(str)
print(str_list)
i = 0
print(len(str_list))

# 从前往后遍历list,如果碰到空格,就调用反转函数,不考虑单个字符情况
while i < len(str_list):
  if str_list[i] != &#39; &#39;:
    start = i
    end = start + 1
    print(end)
    while (end < len(str_list)) and (str_list[end]!=&#39; &#39;):
      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(&#39;&#39;.join(str_list))

# 采用正则表达式操作
str_re = re.split(r&#39;(\s+)&#39;,str)

str_re.reverse()
str_re = &#39;&#39;.join(str_re)
print(str_re)

The above is the detailed content of Python implements word reversal effect. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn