5

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]
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Stiggo
  • 1,047
  • 1
  • 10
  • 12
  • reverse the entire string. then reverse (back) each individual word. – jb. May 24 '12 at 21:33
  • Just write your own split then. – Jeffrey Greenham May 24 '12 at 21:36
  • @FallenAngel Nope. As you can see I've got a solution, I'm just curious about other solutions. – Stiggo May 24 '12 at 21:37
  • If str.split() in particular is not allowed, there are various ways the re module can help. – Bittrance May 24 '12 at 21:38
  • 3
    If it's not a homework assignment, in what sense is split() "not allowed"? – Mark Reed May 24 '12 at 21:39
  • @Stiggo, if it is a homework, then it must be *you* who solve it, and everybody in here will guide you to different approaches, but not write down the complete code... – Mp0int May 24 '12 at 21:46
  • 2
    I'm with Mark Reed. Even if it's not technically homework, clearly it's some kind of artificial toy challenge rather than a real-world task. In the real world, the Pythonic way is the simplest, most obvious way, and that way is to use `split()` to get the words. – John Y May 24 '12 at 21:52
  • @FallenAngel It is not a hw. I thought it would be a good idea to ask for a better solution. Maybe someone show me a cool oneliner trick or so. But clearly I was wrong. – Stiggo May 24 '12 at 21:54

10 Answers10

4
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(' ')
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • 1
    I think the last line should be `answer.rstrip(' ')` otherwise the returned result will contain a trailing space which wasn't in the original string. So full last line should read: `return answer.rstrip(' ')`. – Lucas Roberts Sep 19 '21 at 21:07
  • @LucasRoberts: you're absolutely right. Thanks for the bugreport – inspectorG4dget Sep 22 '21 at 14:53
3

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.

Casey Kuball
  • 7,717
  • 5
  • 38
  • 70
0

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"
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
0
>>> 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'
airstrike
  • 2,270
  • 1
  • 25
  • 26
  • Using `re.split` instead of `str.split`? Well, **if it were homework**, the teacher **wouldn't be** very happy about this trick :) – Lev Levitsky May 24 '12 at 22:54
0

Use re

import re
myStr = "Here is sample text"
print " ".join(re.findall("\S+",myStr)[::-1])
0

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)
Zart
  • 1,421
  • 10
  • 18
0

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)
Jared Wilber
  • 6,038
  • 1
  • 32
  • 35
0

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")
ssulav
  • 69
  • 4
0

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

'''

ayushi
  • 3
  • 1
-3

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.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180