5

这样做的pythonic方法是什么?

从这个:'This is a string to try' 到 this:'try to string a is This'

我的第一个猜测是:

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

str.split()是不允许的。然后我想出了这个:

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]
4

9 回答 9

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(' ')
于 2012-05-24T21:41:43.840 回答
3

这是一个 O(n) 实现(不使用连接 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))

这从字面上实现了拆分算法——手动将字符串拆分为单词,然后反转单词列表。

于 2012-05-24T22:42:45.743 回答
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'

按要求提供一个班轮('import re' 位除外):

>>> 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'
于 2012-05-24T22:40:50.253 回答
0

创建一个向后遍历字符串的循环,使用字符串索引来获取每个字符。请记住,在 Python 中,您可以使用以下命令访问字符串:

s = "Strings!"
sOne = s[1] // == "t"
于 2012-05-24T21:36:04.813 回答
0

在某些采访中,您在使用 Python 时会受到限制,例如不要使用reversed[::-1].split().

在这些情况下,下面的代码Python 2.7可以工作(从上面 Darthfett 的回答中采用):

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)
于 2017-03-07T07:13:29.403 回答
0

使用重新

import re
myStr = "Here is sample text"
print " ".join(re.findall("\S+",myStr)[::-1])
于 2015-12-16T10:51:08.377 回答
0

如果允许 string.partition 作为替换:

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

否则回退到 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)
于 2015-12-16T11:16:08.477 回答
0

不使用任何内置方法的最简单程序:

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")
于 2018-03-07T16:43:45.833 回答
-3

编辑:好吧,如果str.split允许的话,就是这样 ;-) 或者,您当然可以编写自己的 split 版本。

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

分为三个步骤:按空格分割,用单词反转列表,将字符串列表连接成一个字符串,中间有空格。

于 2012-05-24T21:35:17.503 回答