Reverse word order of a string with no str.split()

2020-07-13 09:41发布

What is the pythonic way to doing this?

From this: 'This is a string to try' to this: 'try to string a is This'

My first guess was:

for w in 'This is a string to try'.split(' ')[::-1]:
    print w,

but str.split() is not allowed. Then I came up with this:

def reverse_w(txt):
    tmp = []
    while (txt.find(' ') >= 0):
        tmp.append(txt[:txt.find(' ')])
        txt = txt[txt.find(' ')+1:]
    if (txt.find(' ') == -1):
        tmp.append(txt)
   return tmp[::-1]

标签: python string
9条回答
等我变得足够好
2楼-- · 2020-07-13 10:27

Here is an O(n) implementation (doesn't use concatenation via +):

def reverse_w(txt):
    words = []
    word = []

    for char in txt:
        if char == ' ':
            words.append(''.join(word))
            word = []
        else:
            word.append(char)
    words.append(''.join(word))

    return ' '.join(reversed(words))

This implements the split algorithm literally -- manually splitting the string into words, and then reversing the list of words.

查看更多
beautiful°
3楼-- · 2020-07-13 10:27

Create a loop that iterates through the string backwards, using string indexing to get each character. Remember, in Python, you can access strings using the following:

s = "Strings!"
sOne = s[1] // == "t"
查看更多
放我归山
4楼-- · 2020-07-13 10:28

Simplest program without using any built in methods :

def reverse(sentence):
    answer = ''
    temp = ''
    for char in sentence:
        if char != ' ':
            temp += char
            continue
        rev = ''
        for i in range(len(temp)):
            rev += temp[len(temp)-i-1]
        answer += rev + ' '
        temp = ''
    return answer + temp
reverse("This is a string to try")
查看更多
登录 后发表回答