converting types

Alex Martelli aleax at aleax.it
Mon May 13 03:52:36 EDT 2002


ian wrote:

> hi i know its a pain answering newbie questions
> that to you lot seem really simple
> 
> but how do i convert an int into a string?

Simplest is str(number) -- there are other ways.  As others
have suggested to you, the % operator, also known as "string
formatting operator", is generally handiest for most kinds
of string preparation tasks --

msg = "List is %s long" % number

You can always use the %s marker in the format string on the
left, it means "convert whatever to string", just like the
builtin str(whatever).  If you have more than one value to
convert, then on the right hand side of % you need a tuple:

msgx = "List is %s long: %s" % (number, somelist)

You may use fancier formatting markers than %s for many
specialized uses (ensure field-width, control the number
of decimal digits when formatting a floating point number,
etc, etc), but these are really advanced issues which you
don't need to worry about for now -- %s will serve!


Alex




More information about the Python-list mailing list