[Tutor] Does casting exist in Python?

Alan Gauld alan.gauld at freenet.co.uk
Thu Feb 23 22:56:53 CET 2006


> Subject: [Tutor] Does casting exist in Python?
> Does it?

That depends on what you mean by casting.
A cast in C literally telly the compiler to treat one piece of data 
as if it were another type of data.

For example

char c = 'a';
float f = (float)c;

Tells C to take the character stored in c and treat it as a floating 
point number. It does not change the type of c it merely treats 
the data as if it were another type.

However in practice many people use casting as a type conversion 
operation and think of it in that light - which often leads to strange 
and subtle bugs!

Python does do type conversion by applying conversion functions 
such as str(), int(), float() list() etc [Actually I believe these are now 
callable types which is subtly different but I'll ignore that for now!]

If you do want to do a cast (ie. re-interpret data) the only way that I 
know of is to use the struct module. That allows you to take a piece 
of data and write it as a byte string, you can then reinterpret the byte 
string using a different format set and effectively the same byte 
sequence that started as a char will be read as a float! (there might 
be issues if the buyte string lengths don;t match....)


HTH,

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld





More information about the Tutor mailing list