String Formatting In Python 2.7
Solution 1:
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
Solution 2:
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
Solution 3:
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 calllast):
File "<stdin>", line 1, in<module>
ValueError: invalid literal forint() with base 10: 's'
It just works on digits :
>>>int('12')
12
Solution 4:
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.
Post a Comment for "String Formatting In Python 2.7"