Noob question: Is all this typecasting normal?

Benjamin Kaplan benjamin.kaplan at case.edu
Fri Jan 2 22:35:52 CET 2009


On Fri, Jan 2, 2009 at 4:15 PM, sprad <jsprad at gmail.com> wrote:

> I've done a good bit of Perl, but I'm new to Python.
>
> I find myself doing a lot of typecasting (or whatever this thing I'm
> about to show you is called), and I'm wondering if it's normal, or if
> I'm missing an important idiom.
>
> For example:
>
> bet = raw_input("Enter your bet")
> if int(bet) == 0:
>    # respond to a zero bet
>
> Or later, I'll have an integer, and I end up doing something like
> this:
>
> print "You still have $" + str(money) + " remaining"
>
> All the time, I'm going int(this) and str(that). Am I supposed to?


The cast to the int is needed. The cast to a string isn't. Use string
formatting instead. As an added bonus, you can ensure that you always show 2
digits past the decimal.

>>> money = 2.1
>>>print "You still have $%0.2f remaining" % money
You still have $2.10 remaining




>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20090102/ca49a5c0/attachment.html>


More information about the Python-list mailing list