开发者

How do you reverse the words in a string using python (manually)? [duplicate]

This question already has answers here: 开发者_开发问答 Closed 11 years ago.

Possible Duplicate:

Reverse the ordering of words in a string

I know there are methods that python already provides for this, but I'm trying to understand the basics of how those methods work when you only have the list data structure to work with. If I have a string hello world and I want to make a new string world hello, how would I think about this?

And then, if I can do it with a new list, how would I avoid making a new list and do it in place?


Split the string, make a reverse iterator then join the parts back.

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

If you are concerned with multiple spaces, change split() to split(' ')


As requested, I'm posting an implementation of split (by GvR himself from the oldest downloadable version of CPython's source code: Link)

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

I think now there are more pythonic ways of doing that (maybe groupby) and the original source had a bug (if i = n:, corrrected to ==)


Original Answer

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()

Answer using list to match updated question

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)

Besides renaming, the only change of interest is the last line.


You have a string:

str = "A long string to test this algorithm"

Split the string (at word boundary -- no arguments to split):

splitted = str.split()

Reverse the array obtained -- either using ranges or a function

reversed = splitted[::-1]

Concatenate all words with spaces in between -- also known as joining.

result = " ".join(reversed)

Now, you don't need so many temps, combining them into one line gives:

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


str = "hello world"
" ".join(str.split()[::-1])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜