如何用Python手动反转字符串中的单词?

1 投票
4 回答
19799 浏览
提问于 2025-04-17 03:55

可能重复的问题:
反转字符串中单词的顺序

我知道Python已经提供了一些方法可以做到这一点,但我想搞清楚这些方法的基本原理,尤其是当我只能使用列表这种数据结构时。如果我有一个字符串 hello world,我想把它变成一个新的字符串 world hello,我该怎么思考这个问题呢?

然后,如果我可以用一个新的列表来实现,那我该如何避免创建新的列表,而是在原地完成这个操作呢?

4 个回答

5

你有一个字符串:

str = "A long string to test this algorithm"

把这个字符串分开(在单词的边界处分开——对split不需要传入任何参数):

splitted = str.split()

把得到的数组反转——可以用范围或者函数来实现。

reversed = splitted[::-1]

把所有的单词用空格连接起来——这也叫做连接。

result = " ".join(reversed)

现在,你不需要那么多临时变量,把它们合并成一行可以得到:

result = " ".join(str.split()[::-1])
14

首先,你可以把字符串分开,接着创建一个反向迭代器,然后再把这些部分合并起来。

' '.join(reversed(my_string.split()))

如果你担心字符串中有多个空格,可以把 split() 改成 split(' ')


应要求,我在这里分享一个分割字符串的实现方法(这是GvR本人在最早的CPython源代码可下载版本中的实现:链接)。

def split(s,whitespace=' \n\t'):
   res = []
   i, n = 0, len(s)
   while i < n:
       while i < n and s[i] in whitespace:
           i = i+1
       if i == n:
           break
       j = i
       while j < n and s[j] not in whitespace:
           j = j+1
       res.append(s[i:j])
       i = j
   return res

我觉得现在有更符合Python风格的方法来实现这个功能(比如使用groupby),而且原始代码中有个小错误(if i = n:,应该改成 ==)。

7

原始回答

from array import array

def reverse_array(letters, first=0, last=None):
    "reverses the letters in an array in-place"
    if last is None:
        last = len(letters)
    last -= 1
    while first < last:
        letters[first], letters[last] = letters[last], letters[first]
        first += 1
        last -= 1

def reverse_words(string):
    "reverses the words in a string using an array"
    words = array('c', string)
    reverse_array(words, first=0, last=len(words))
    first = last = 0
    while first < len(words) and last < len(words):
        if words[last] != ' ':
            last += 1
            continue
        reverse_array(words, first, last)
        last += 1
        first = last
    if first < last:
        reverse_array(words, first, last=len(words))
    return words.tostring()

使用 list 来匹配更新的问题的回答

def reverse_list(letters, first=0, last=None):
    "reverses the elements of a list in-place"
    if last is None:
        last = len(letters)
    last -= 1
    while first < last:
        letters[first], letters[last] = letters[last], letters[first]
        first += 1
        last -= 1

def reverse_words(string):
    """reverses the words in a string using a list, with each character
    as a list element"""
    characters = list(string)
    reverse_list(characters)
    first = last = 0
    while first < len(characters) and last < len(characters):
        if characters[last] != ' ':
            last += 1
            continue
        reverse_list(characters, first, last)
        last += 1
        first = last
    if first < last:
        reverse_list(characters, first, last=len(characters))
    return ''.join(characters)

除了重命名之外,唯一值得注意的变化就是最后一行。

撰写回答