python - 在不允许 str.split() 的情况下反转字符串的词序

标签 python string

执行此操作的 pythonic 方法是什么?

从这个:'This is a string to try'到这个:'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]

最佳答案

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

关于python - 在不允许 str.split() 的情况下反转字符串的词序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10745593/

相关文章:

python : saving variables from a text file created

python - 将变量传递给索引函数 - Python

python - 有没有办法读取字符串并将字符串中的每个字母转换为另一个字符串中的项目?

c - 如何将标准输出重定向到 ANSI C 中的字符串

Python套接字编程: Upload files from Client to Server

python - Tensorflow:无法共享密集/内核 - ValueError:尝试共享变量密集/内核,但指定形状 (100, 160) 并找到形状 (9, 100)

python - 张量 u'real_images :Cannot feed value of shape (40, 24, 24, 3)' 的 Tensorflow ValueError : 0', which has shape ' (40, 24, 24, 4)'

java - 如何在java中存储列表中匹配的元素

javascript - 使用 jQuery 在字符串中的每个单词前添加 "+"

string - 检查字符串是否以 Emacs Lisp 中的后缀结尾