Python 倒车功能工作不正常

Python 倒车功能工作不正常,python,python-3.x,python-3.4,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 = str

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

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
Hello中缺少“o”。我哪里出错了?

简单一点

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


您需要稍微修改您的循环

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
def反转(字符串):
words=string.count(“”+1
计数=1
string_reversed=“”
而计数<字:
string\u reversed=第一个单词(string)+str(“”+string\u reversed
字符串=最后一个单词(字符串)
计数+=1
打印(字符串+“”+字符串\u反转)
返回字符串+“”+字符串\u反转

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

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

您的问题与此代码有关:

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

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

任务是使用两个不同的函数来创建它,因此我不能使用joinNo问题是说明是先使用函数,然后使用最后一个词,如果我有选择的话,我会用另一种方式。请帮我做这件事it@HelloWorld:如果您只能描述函数的作用->
第一个单词(…)
做什么?反转列表中的第一个单词?返回字符串的第一个字?(尽管从您的代码中可以明显看出这一点;您可以对其进行改进:
def first\u word(s):返回s.split(“”[0]
)。请不要将
string
用作参数,因为它可能会与内置的
string
模块产生阴影。(即使现在不是这种情况)first\u word()返回字符串的第一个单词和最后一个单词()返回字符串的其余部分每次打印第一个单词时会发生什么?它是显示Hell还是Hello?你的意思是当我反转(“Hello”)时?它后面有空格显示Hell不,在返回第一个单词之前,请将其打印出来。看到会发生什么吗?第一个单词(“Hello,我的名字是Bob”)产生Hellof或我,你编码打印
Bo is name my Hello
现在当我反转(“你好,我的名字是Bob”)时,它返回“Bo is”请看,我现在做了一个更改现在我得到了“is name my Hello Bob”这个打印Bob is name my Hello我恐怕他必须使用自己的函数
def first_word(string):
    first_space_pos = string.find(" ")
    word = string[0:first_space_pos]
    return word
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