20
votes
print ("Hello World")
print ("{} World").format(Hello)

I'm working on my first "Hello World" program and I can get it to work by using the print function and just a simple string text but when I try to use .format it gives me the error:

AttributeError: 'NoneType' object has no attribute 'format' 

Is this saying that I need to initialize a variable for .format or am I missing something?

3

3 Answers

41
votes

Your brackets are wrong

print("Hello World")
print("{} World".format('Hello')) 

Note - the errors

  • The format function is an attribute of str so it needs to be called on the string
  • Unless declared, Hello is a string and should be 'Hello'

For Py2 you can do

print "{} World".format('Hello') 
1
votes

Function print returns None, so that's obviously what you're getting from the start of your second statement, namely

print ("{} World")

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

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.

Moreover, is Hello the name of a variable whose value you want to format? I sure hope not, else why haven't 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 it's 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...!

0
votes

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

Example

fmt = '{:^9}|{:^13}|{:^18}'
data = [1, None, 'test']

print(fmt.format(*data))

Python2.7

$ python2.7 test
    1    |    None     |       test

In Python3.6

python3.6 test
Traceback (most recent call last):
  File "test", line 5, in <module>
    print(fmt.format(*data))
TypeError: unsupported format string passed to NoneType.__format__

But if we remove the format's features of column-width

fmt = '{}|{}|{}'
data = [1, None, 'test']

print(fmt.format(*data))

OR convert all values to Strings using !s

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

It works just fine in both versions ...