Home > Article > Backend Development > Python implements word reversal effect
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 = ' I love china! ' str_list = list(str) print(str_list) i = 0 print(len(str_list)) # 从前往后遍历list,如果碰到空格,就调用反转函数,不考虑单个字符情况 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)) # 采用正则表达式操作 str_re = re.split(r'(\s+)',str) str_re.reverse() str_re = ''.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!