繁体   English   中英

反向功能无法正常工作

[英]Reverse function not working properly

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

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

Hello中缺少“ o”。 我哪里做错了?

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

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

把事情简单化,

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

要么

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

您需要稍微修改循环

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM