Search code examples
pythonstringword-wrap

Why am I getting a "None" at the end of the output while computing textwrap module in Python?


Although I am defining my function as below:

import textwrap

def wrap(string, max_width):
    print(textwrap.fill(string, max_width))

if __name__ == '__main__':
    string, max_width = input(), int(input())
    result = wrap(string, max_width)
    print(result)

I am getting an error like:

*ABCD
EFGH
IJKL
IMNO
QRST
UVWX
YZ
None*

Can you please help me to debug why this "None" or how is this value getting augmented with the output.


Solution

  • You are printing twice. Once in the function, and then again the return value of the function. The None is coming from the second print.

    Do this:

    import textwrap
    
    def wrap(string, max_width):
        return textwrap.fill(string, max_width) # return , don't print
    
    if __name__ == '__main__':
        string, max_width = input().rstrip(), int(input())
        result = wrap(string, max_width)
        print(result)