我应该怎么做才能让我的代码不打印"None"?



在这个问题中,我必须根据给定的宽度值换行文本。一切都进展顺利,直到程序最后打印"无"的最后一部分。

我试图制作一个新列表并附加,但这效果不佳。代码如下:

import textwrap
def wrap(string, max_width):
    i = max_width
    j=0
    length = len(string)
    while j<length:    
        word = string[j:i]
        i = i+max_width
        j = j + max_width
        print(word)
string, max_width = input(), int(input())
result = wrap(string, max_width)
print(result)

目的是使功能正确。一切都很好,直到程序最后打印"无"。

示例输入ABCDEFGHIJKLIMNOQRSTUVWXYZ四

示例输出
ABCD
埃夫格
IJKL
伊诺
QRST
UVWX
YZ

我的输出:
ABCD
埃夫格
IJKL
伊诺
QRST
UVWX
YZ
没有

当你从函数返回时,函数是 DONE - while 循环是没有意义的 - 如果它进入 while 循环,它会返回一个单词 - 它不会循环。

def wrap(string, max_width):
    i = max_width
    j=0
    length = len(string)
    while j<length:    
        word = string[j:i]
        i = i+max_width
        j = j + max_width
        return word             # leaves as soon as it reaches this
    # if j not < length returns None implicitly

如果它没有进入 while 循环,则不返回任何内容,因此您的函数隐式返回None


如果你想从你的函数返回多个结果,你可以把它作为一个生成器并产生结果:

def wrap(text,width):
    start = 0
    lentext = len(text)
    while start < lentext:  # while still stuff to yiled
        yield text[start:start+width]
        start += width   # next time start +width further to the right
string, max_width = "ABCDEFGHIJKLIMNOQRSTUVWXYZ", 4
print(*wrap(string,max_width), sep="n")

输出:

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

您可以使用列表理解来换行文本:

string, max_width = "ABCDEFGHIJKLIMNOQRSTUVWXYZ", 4
result = [string[i:i+max_width] for i in range(0,len(string),max_width)]

print(*result, sep="n")

输出:

ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ

列表补偿解决方案在这里更详细地介绍: 如何将列表拆分为大小均匀的块? - 列表和字符串"相似",如: 两者都是可迭代对象。

最新更新