5

Hello i am currently learning how to use string formatting in python 2.7 and im slightly confused on a certain error message that gets produced in a particular scenario.

  1. Ok so the first piece of code that i have written runs as expected which is:

    print "My name is %s and my age is %d years old!" % ('Bob', 30)
    
  2. The second piece of slightly altered code also runs fine which is (using two (s) conversions) :

    print "My name is %s and my age is %s years old!" % ('Bob', 30)
    
  3. However the third piece of code outputs and error (using one (d) and one (s) conversions) :

    print "My name is %d and my age is %s years old!" % ('Bob', 30)
    

In scenario 3 I get the error message:

%d format: a number is required, not str

So my question is why is scenario 2 allowed (placing (s) conversion on an expected decimal) but the other way round in scenario 3 is not allowed. Thanks and i hope i explained my question as best as possible.

3
  • 4
    You can convert an integer to string, but not vice versa. Commented Jul 13, 2015 at 11:51
  • Because, a decimal can be converted to a string but a string can not be converted to a decimal. In your case you are trying to cast 'Bob' to %d. Commented Jul 13, 2015 at 11:56
  • FYI Just wanted to note the introduction of formatting with of %d and %s came when c language's printf function and these specifiers are: %d - decimal (integer) number (base 10) %s - a string of characters Commented Jul 27, 2021 at 20:22

4 Answers 4

11

There is a better way to format strings in python (may interest you). It doesn't matter the object type. By list

"{0}-{1}: {2}".format(1,"foo",True)

By dict

"{num}-{string}: {bool}".format(**{"num":1,"string":"foo","bool":True})

More info: https://docs.python.org/2/library/stdtypes.html#str.format

Sign up to request clarification or add additional context in comments.

Comments

7

it should be

print "My name is %s and my age is %d years old!" % ('Bob', 30)

The error was thrown because it expected integer value that is %d but got a string %s

But int can be converted into string so previous case was not affected

5 Comments

I understand that, if you look in scenario 1 you will see i have given that example and said that it ran fine. But my question is why is scenario 2 allowed ie; placing a (s) conversion on a expected decimal but the other way round ie; placing a (d) conversion on an expected string isn't allowed.
@at541 it is because when %s is called an implicit str() is run on the value but not inthe case of %d
Ok thanks i see the edit now in your answer so it made more sense.
@at541 if this answered the question can you accept it
Yes , and thanks everyone else who gave me some more insight as well. As you were the first to explain the reasoning fully Vignesh ,i will gladly accept your answer.
2

It's because of that %s converts another python types to string using str() function. but %d just accept an integer decimal.

For more information read String Formatting Operations.

Also note that you can convert any number to string without Error but you can not convert any string to integer because it may raise a ValueError :

>>> int('s')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 's'

It just works on digits :

>>> int('12')
12

Comments

1

In scenario 1, python does an implicit cast from integer to double. So far so good.

In scenario 2, python does an implicit cast from integer to string, which is possible. However in case 3, python would have to cast a string consisting of chars to double, which is not possible.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.