Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 214
MonotonousSonder Avatar asked Feb 07 '15 03:02

MonotonousSonder


People also ask

What is a NoneType object?

NoneType in Python is a data type that simply shows that an object has no value/has a value of None . You can assign the value of None to a variable but there are also methods that return None .

How do you handle Typeerror NoneType object is not Subscriptable?

None always has no data and can not be subscriptable. In general, the error means that you attempted to index an object that doesn't have that functionality. You might have noticed that the method sort() that only modify the list have no return value printed – they return the default None.


2 Answers

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')  
like image 144
Bhargav Rao Avatar answered Oct 16 '22 10:10

Bhargav Rao


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...!

like image 42
Alex Martelli Avatar answered Oct 16 '22 12:10

Alex Martelli