converting an integer to a string

S

Skip Montanaro

Ken> I have a quick simple question. How do you convert an integer to a
Ken> string in Python?

Take your pick:

str(someint)
repr(someint)
`someint`
'%d' % someint

Which is most appropriate may well depend on your tastes and your context.
`someint` is just syntactic sugar for repr(someint), and is falling out of
favor with many people. In the case of integers, str(someint) and
repr(someint) are the same, so your choice there is a tossup unless you are
str()'ing or repr()'ing other objects as well (str() generally tries to be
"readable", repr() generally tries to be "parseable"). For most types
repr() and str() generate different output. The experiment is probably
educational enough to perform once, so I won't go into detail.

The %-format version is appropriate if you want to embed it into a larger
string, e.g.:

'%s is %d years old' % (person, age)

Don't forget the dict form as well:

'%(name)s is %(age)d years old' % locals()

Skip
 
J

John Roth

Skip Montanaro said:
Ken> I have a quick simple question. How do you convert an integer to a
Ken> string in Python?

Take your pick:

str(someint)
repr(someint)
`someint`
'%d' % someint

Which is most appropriate may well depend on your tastes and your context.
`someint` is just syntactic sugar for repr(someint), and is falling out of
favor with many people. In the case of integers, str(someint) and
repr(someint) are the same, so your choice there is a tossup unless you are
str()'ing or repr()'ing other objects as well (str() generally tries to be
"readable", repr() generally tries to be "parseable"). For most types
repr() and str() generate different output. The experiment is probably
educational enough to perform once, so I won't go into detail.

The %-format version is appropriate if you want to embed it into a larger
string, e.g.:

'%s is %d years old' % (person, age)

Don't forget the dict form as well:

'%(name)s is %(age)d years old' % locals()

The % format also allows you some formatting options that the others
don't.

John Roth
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top