Saturday, August 1, 2009

Python: Convert integer into string


Share at Facebook

Python is not like other script language. Its strongly against the variable types mismatch. For example at other scripting language, you can easily assign an integer into a string type of variable. Or concat them easily with concatination operators.

But at python, you can not concat a string with an integer until you are making them both string. If you try to do that, you'll get an error like below.

TypeError: cannot concatenate 'str' and 'int' objects


You must need to convert your integer into string. If you are a new at Python, that will be difficult for you to find the simple str() function that will convert your integer to string. Here is a code which using str() function to do that.
integer = 10
string = "ten"
output = string + str(integer)
print output




3 comments:

Anonymous said...

Thanks!

TJ Locke said...

Thank you for having this readily available. You were right, that is not an easy function to come across looking through the python documentation.

The Calm Crisis
http://calmcrisis.wordpress.com/

happystain said...

Another option is to use backticks/accents located on the ~ (tilde) key. This has the effect of translating python objects into a string. Just put them around the python object (in this case `x`) when concatenating with a string. A drawback is that you lose control over the format of how the object is displayed.

Example 1:
>>> x = 3
>>> 'object: ' + `x`
"object: 3"

Example 2:
>>> x = [3,4,'asdf']
>>> 'object: ' + `x`
"object: [3, 4, 'asdf']"

Example 3:
>>> def x():
... print 'nothing'
...
>>> x()
nothing
>>> x
<function y at 0x009F9F30>
>>> 'object: ' + `x`
'object: <function x at 0x009F9F30>'