August 16, 2011
Python Concatenating Strings and Numbers
I am a new Python programmer. I have a simple problem when try to concatenating strings and numbers in Python. For example, I create this this script :
a = 'I have ' b = 5 c = 'apples' d = a + b + c print d
When I try to running this script, I have this errorĀ message :
Traceback (most recent call last): File "tes.py", line 5, in <module> d = a + b + c TypeError: cannot concatenate 'str' and 'int' objects
This error show because we want to concatenating strings and numbers in Python. If we want to solve this problem,we can use string formating in Python. This is like in C/C++ or other language programming. We can solve problem above about concatenating strings and numbers in Python with this code :
a = 'I have ' b = 5 c = 'apples' d = a + '%i ' %b + c print d
This is ouput from concatenating strings and numbers in Python code above :
I have 5 apples
This is a table string formating conversion in Python from other data type :
Conversion | Meaning |
---|---|
d | Signed integer decimal. |
i | Signed integer decimal. |
o | Unsigned octal. |
u | Unsigned decimal. |
x | Unsigned hexidecimal (lowercase). |
X | Unsigned hexidecimal (uppercase). |
e | Floating point exponential format (lowercase). |
E | Floating point exponential format (uppercase). |
f | Floating point decimal format. |
F | Floating point decimal format. |
g | Same as “e” if exponent is greater than -4 or less than precision, “f” otherwise. |
G | Same as “E” if exponent is greater than -4 or less than precision, “F” otherwise. |
c | Single character (accepts integer or single character string). |
r | String (converts any python object using repr()). |
s | String (converts any python object using str()). |
% | No argument is converted, results in a “%” character in the result. |