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. |
5 Comments
Your point of view caught my eye and was very interesting. Thanks. I have a question for you.
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me?
Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.bh/register?ref=IHJUI7TF
Can you be more specific about the content of your article? After reading it, I still have some doubts. Hope you can help me. https://www.binance.bh/register?ref=JW3W4Y3A
[1172]999jl Official Login | Best Online Slots PH with GCash Deposit,999jl offers a secure portal for app downloads and easy GCash payments. Learn how to play baccarat and win big on top games. Join the action and sign up today! visit: 999jl