python - AttributeError: NoneType object has no attribute format

python – AttributeError: NoneType object has no attribute format

python – AttributeError: NoneType object has no attribute format

Your brackets are wrong

n

print(Hello World)nprint({} World.format(Hello)) n

n

Note – the errors

n

    • n

    • The format function is an attribute of str so it needs to be called on the string

n

    • Unless declared, Hello is a string and should be Hello

n

n

For Py2 you can do

n

print {} World.format(Hello) n

Function print returns None, so thats obviously what youre getting from the start of your second statement, namely

n

print ({} World)n

n

On that return value of None, you then call .format(Hello) — even if a variable named Hello was assigned somewhere in your code (and youre not showing it to us!), youre calling that .format method on the None returned from your print call, which makes no sense.

n

Rather, you want to call .format on the string {} World — so the closed-paren right after the string and before the dot is clearly a terrible mistake! Move that ) to the end of the statement, after the call to format on that string.

n

Moreover, is Hello the name of a variable whose value you want to format? I sure hope not, else why havent you shown us that variable being assigned?! I suspect you want to format a constant string and just absent-mindedly forgot to put it in quotes (to show its a constant, not the name of a variable!) — Hello, not Hello without quotes! That is what you should be passing to the proper form of the .format call…!

python – AttributeError: NoneType object has no attribute format

even thought the requestor of the original question was wrong in using the .format structure – I believe hes still right about one thing – the behavior in Python3 is different when having a value that equals None

n

Example

n

fmt = {:^9}|{:^13}|{:^18}ndata = [1, None, test]nnprint(fmt.format(*data))n

n

Python2.7

n

$ python2.7 testn    1    |    None     |       testn

n

In Python3.6

n

python3.6 testnTraceback (most recent call last):n  File test, line 5, in <module>n    print(fmt.format(*data))nTypeError: unsupported format string passed to NoneType.__format__n

n

But if we remove the formats features of column-width

n

fmt = {}|{}|{}ndata = [1, None, test]nnprint(fmt.format(*data))n

n

OR convert all values to Strings using !s

n

fmt = {!s:^9}|{!s:^13}|{!s:^18}n

n

It works just fine in both versions …

Related posts on Attribute Error  :

Leave a Reply

Your email address will not be published.