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

Question:

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]
Asked By: Stiggo

||

Answers:

Edit: well, if str.split were allowed, it would be this 😉 Alternatively, you could write your own version of split of course.

>>> s = 'This is a string to try'
>>> r = s.split(' ')
['This', 'is', 'a', 'string', 'to', 'try']
>>> r.reverse()
>>> r
['try', 'to', 'string', 'a', 'is', 'This']
>>> result = ' '.join(r)
>>> result
'try to string a is This'

There are three steps: split by space, reverse the list with words and concatenate the list of strings to one string with spaces in between.

Answered By: Simeon Visser

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"
Answered By: SomeKittens
def reverse(sentence):
sentence = 'This is a string to try'
    answer = ''
    temp = ''
    for char in sentence:
        if char != ' ':
            temp += char
        else:
            answer = temp + ' ' + answer
            temp = ''
    answer = temp + ' ' + answer
    return answer.rstrip(' ')
Answered By: inspectorG4dget
>>> import re
>>> s = 'This is a string to try'
>>> z = re.split('W+', s)
>>> z.reverse()
>>> ' '.join(z)
'try to string a is This'

One liner (except for the ‘import re’ bit) as requested:

>>> reduce(lambda x, y: u'%s %s' % (y, x), re.split('W+', 'This is a string to try'))
u'try to string a is This'
Answered By: airstrike

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.

Answered By: Casey Kuball

Use re

import re
myStr = "Here is sample text"
print " ".join(re.findall("S+",myStr)[::-1])
Answered By: abhishek Sharma

If string.partition is allowed as a replacement:

def reversed_words(s):
    out = []
    while s:
        word, _, s = s.partition(' ')
        out.insert(0, word)
    return ' '.join(out)

otherwise fallback on string.find:

def reversed_words(s):
    out = []
    while s:
        pos = s.find(' ')
        if pos >= 0:
            word, s = s[:pos], s[pos+1:]
        else:
            word, s = s, ''
        out.insert(0, word)
    return ' '.join(out)
Answered By: Zart

In some interviews you’re constrained when using Python, e.g. don’t use reversed, [::-1], or .split().

In those cases, the following code in Python 2.7 can work (adopted from Darthfett’s answer above):

def revwords(sentence):
    word = []
    words = []

    for char in sentence:
        if char == ' ':
            words.insert(0,''.join(word))
            word = []
        else:
            word.append(char)
    words.insert(0,''.join(word))

    return ' '.join(words)
Answered By: Jared Wilber

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")
Answered By: ssulav

Its a bit long version.

”’

sen ="sharing is caring"
def reverse(sen):
    n = len(sen)
    sen_ = list(sen)
    for i in range(n//2):
        sen_[i],sen_[n-1-i] = sen_[n-1-i],sen_[i]
    return sen_
    
def split(sen):
    n = len(sen)
    # l = 0
    r = 0
    words = []
    temp = []
    while r < n:
        if sen[r] == " ":
            words.append(temp)
            temp =[]
        else:
            temp.append(sen[r])
            if r == n -1:
                words.append(temp)
        r +=1  
    return words


def join(sen_,delimeter=" "):
    s = ""
    for i in sen_:
        for j in i:
            s +=j
        s+=delimeter
    return s

def reverse_words_string(sen):
    sen = reverse(sen)
    sen = split(sen)
    sen =[reverse(i) for i in sen]
    sen = join(sen)
    return sen

print(reverse_words_string(sen))

”’

Answered By: ayushi
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.