Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: unsupported operand type(s) for %: 'NoneType' and 'str'

So I am VERY new to programming and I started with Python 3. I started reading "Learn Python the Hard Way". Now, I got to a point where I had this code:

x = "There are %d types of people." % 10 binary = "binary" do_not = "don't" y = "Those who know %s and those who %s" % (binary, do_not)  print(x) print(y) print("I said: %r") % x 

I do not really know the difference between %r, %s and %d. The error I get is TypeError: unsupported operand type(s) for %: 'NoneType' and 'str' No idea what to do and how to fix it. Please explain how I can actually make it work and why it won't work. Also, what is the difference between %r,d and s? Any useful links? Thank you in advance.

like image 396
user3586591 Avatar asked Apr 29 '14 18:04

user3586591


People also ask

How do I fix unsupported operand type in Python?

The Python "TypeError: unsupported operand type(s) for /: 'str' and 'int'" occurs when we try to use the division / operator with a string and a number. To solve the error, convert the string to an int or a float , e.g. int(my_str) / my_num .

What does unsupported operand type S for +: int and STR?

The Python "TypeError: unsupported operand type(s) for +: 'int' and 'str'" occurs when we try to use the addition (+) operator with an integer and a string. To solve the error, convert the string to an integer, e.g. my_int + int(my_str) . Here is an example of how the error occurs. Copied!

What does unsupported operand types mean?

The TypeError: unsupported operand type(s) for +: 'int' and 'str' error occurs when an integer value is added with a string that could contain a valid integer value. Python does not support auto casting. You can add an integer number with a different number. You can't add an integer with a string in Python.


1 Answers

You want to apply % to the string instead:

print("I said: %r" % x) 

Your code is applying it to the return value of the print() call, which returns None.

Alternatively, you can switch to using str.format():

print("I said: {!r}".format(x)) 
like image 95
Martijn Pieters Avatar answered Oct 02 '22 22:10

Martijn Pieters