[Tutor] casting

Steven D'Aprano steve at pearwood.info
Sun Sep 23 17:28:14 CEST 2012

On 24/09/12 00:44, Gina wrote:
> what is casting?

Depends on the context.

I presume you're talking about programming, not movie-making.

Without knowing the context, it's hard to tell exactly what people
mean when they say "cast", but as a rough translation, you won't be
terribly far wrong if you take is to mean "convert from one kind of
data to a different kind" (e.g. convert an integer to a string).

In some contexts, "cast" means to tell the compiler to treat a
variable as a different type. For example, suppose you have a 16-bit
integer (a "short") with the value 19781. If you cast it to a string
("array of two chars"), it will be treated as the string "ME".

The point about casting in this case is that the compiler doesn't
have to convert the data, it just treats it as a different kind of
value. The actual bits remain exactly the same.

But in *other* programming languages, "cast" is just a synonym for
"convert", and the bits may not be the same (and probably aren't).
In *those* languages, casting the integer 19781 to a string gives
five digits, not two, "19781". Python is one of those languages.


More information about the Tutor mailing list