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:07

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)
查看更多
闹够了就滚
3楼-- · 2020-07-13 10:14

Use re

import re
myStr = "Here is sample text"
print " ".join(re.findall("\S+",myStr)[::-1])
查看更多
我只想做你的唯一
4楼-- · 2020-07-13 10:20

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)
查看更多
狗以群分
5楼-- · 2020-07-13 10:22
>>> 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'
查看更多
Evening l夕情丶
6楼-- · 2020-07-13 10:24
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
查看更多
爷、活的狠高调
7楼-- · 2020-07-13 10:24

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.

查看更多
登录 后发表回答