Python |在执行while循环时返回none

2024-04-27 07:54:45 发布

您现在位置:Python中文网/ 问答频道 /正文

# Let's put it all together. Write code for the function process_madlib, which takes in 

一个字符串“madlib”,并返回字符串“processed”,其中 **#“NOUN”替换为一个随机名词,“VERB”的每个实例都是替换为随机动词。您可以自由更改随机函数 **#以动词或名词的形式返回是为了您自己的乐趣,但是对于提交,请保持代码的原样!****在

^{pr2}$

**

test_string_1 = "ds NOUN ds"
test_string_2 = "I'm going to VERB VERB to the store and pick up a NOUN or two."
print process_madlib(test_string_1)
print process_madlib(test_string_2)

如果我手动测试并将“i”全部更改为“良好”,则始终不返回“none”

编辑:添加代码。。。。。。在

你可以阅读评论中的说明


Tags: theto字符串代码teststringds动词
2条回答

看起来你把“lenght”拼错了。它应该是“长度”。在

除此之外,我想你想用的是len(我)。 这是中间的代码。在

while text[i:len(text)+1] !='':
    i +=1
    if text[i:len(text)+1] == "NOUN":
        proc= text[i:-1] + word_transformer("NOUN") + text[i+len(text):]
        return proc

根据阿兰·菲的评论编辑。在

{{1>你应该使用一个的循环,而不是使用cd1}的代码。另外,您在错误的位置递增i。在

以下是一个有效的版本:

def process_madlib(text):
    proc = ""
    lenght = len("NOUN")
    i = 0
    while text[i:lenght + i] != '':
        if text[i:lenght + i] == "NOUN":
            proc = text[i:-1] + word_transformer("NOUN") + text[i + lenght:]
            return proc
        i += 1
    return text


test_string_1 = "NOUN ds"
test_string_2 = "I'm going to VERB to the store and pick up a NOUN or two."
print(process_madlib(test_string_1))
print(process_madlib(test_string_2))

相关问题 更多 >