Noob question: Is all this typecasting normal?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Sat Jan 3 16:19:58 CET 2009


sprad a écrit :
> 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),

Actually, it's just plain object instanciation.

> 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

raw_input() returns a string. If you want an int and the string is 
supposed to contain a legitimate string representation of an integer, 
then yes, passing the string to the int object constructor is the right 
thing to do. I'd just write it a bit diffently:

bet = int(raw_input("Enter your bet"))
if bet == 0:
    # code here

or even better:

def read_int(prompt, err="Sorry, '%s' is not a valid integer"):
    while True:
       answer = raw_input(prompt)
       try:
            return int(answer)
       except ValueError:
            print err % answer

bet = read_int("Enter your bet")
if bet == 0:
     # code here

> Or later, I'll have an integer, and I end up doing something like
> this:
> 
> print "You still have $" + str(money) + " remaining"

May suggest learning about string formatting ?

    print "You still have $%s remaining" % money


But indeed, you obviously cannot add strings with numerics nor 
concatenate numerics with strings. This would make no sense.

> All the time, I'm going int(this) and str(that). Am I supposed to?

Depends on the context.



More information about the Python-list mailing list