反向功能无法正常工作

时间:2015-11-11 02:37:16

标签: python python-3.x python-3.4

我创建了自己的函数来反转短语中的单词,例如:

reverse("Hello my name is Bob")
Bob is name my Hello

这是我的代码

def first_word(string):
    first_space_pos = string.find(" ")
    word = string[0:first_space_pos]
    return word

def last_words(string):
    first_space_pos = string.find(" ")
    words = string[first_space_pos+1:]
    return words

def reverse(string):
    words = string.count(" ") +1
    count = 1
    string_reversed = ""
    while count <= words:
        string_reversed = first_word(string) + str(" ") + string_reversed
        string = last_words(string)
        count += 1
    return string_reversed

每当我输入一个字符串时,该短语第一个单词的最后一个字母总是被切断

reverse("Hello my name is Bob")
Bob is name my Hell

&#34; o&#34;你好。我哪里出错了?

4 个答案:

答案 0 :(得分:2)

虽然您可以使用[:: - 1]来获取反向列表,但您也可以使用reversed,因为它更具可读性和显性。

>>> words = "Hello my name is Bob"
>>> ' '.join(reversed(words.split(' ')))
'Bob is name my Hello'

答案 1 :(得分:1)

保持简单,

>>> ' '.join("Hello my name is Bob".split()[::-1])
'Bob is name my Hello'

OR

>>> l = "Hello my name is Bob".split()[::-1]
>>> s = ""
>>> for i,j in enumerate(l):
    if i != 0:
        s += ' ' + j
    else:
        s += j


>>> s
'Bob is name my Hello'
>>> 

答案 2 :(得分:1)

你需要稍微修改你的循环

def reverse(string):
words = string.count(" ") +1
count = 1
string_reversed = ""

while count < words:

    string_reversed = first_word(string) + str(" ") + string_reversed

    string = last_words(string)

    count += 1

print(string + " " + string_reversed)
return string + " " + string_reversed

答案 3 :(得分:1)

您的问题在于此代码:

def first_word(string):
    first_space_pos = string.find(" ")
    word = string[0:first_space_pos]
    return word

当你在reverse函数中进行循环迭代时,你发送一个没有任何空格的字符串(因为你的字符串包含要处理的最后一个字),所以string.find(" ")是返回-1。最简单的解决方案是用以下内容替换它:

def first_word(string):
    first_space_pos = string.find(" ")
    if first_space_pos == -1:
        first_space_pos = len(string)
    word = string[0:first_space_pos]
    return word

(假设您必须修改并使用上述功能 - 其他答案提供了更好的方法来实现功能)