Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

python - Defined function keeps returning None, despite having a print() specified within the return line

import textwrap
def wrap(string, max_width):
    i = textwrap.wrap(string, width=max_width)
    print(i)
    z = print(*i, sep='
')
    return z

string, max_width = 'ABCFSAODJIUOHFWRQIOJAJ', 4 
result = wrap(string, max_width) 
print(result)

I am trying to write a code that separates a string in a list, and then prints out each part of the list as a separate line. It works fine until the last bit, where it still attaches None after running the code. I have tried all sorts of ways, but I cannot seem to force my definition to avoid the None.

question from:https://stackoverflow.com/questions/65876316/defined-function-keeps-returning-none-despite-having-a-print-specified-within

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

print returns None, and by returning it, your wrap function would also return None. It seems like you want to join i with a newline:

def wrap(string, max_width):
    i = textwrap.wrap(string, width=max_width)
    return '
'.join(i)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...