Friday, September 10, 2010

Converting Data Types in Python

If you remember so far we have mentioned three types, int, float, and str. For those who don't remember int is integer and is a whole number integer (3 and 91 for example). Float is floating point and has a decimal value (7.2 or even 9.0) and str is string or a string of characters ("Hello, World" is a string). To convert between types Python allows the following:

Convert to integer:
>>>int("29")
29

>>>x=5
>>>int(x)
5

>>>int(3.14159)
3

Convert to float:
>>>float("3.14159")
3.14159

>>>float 5
5.0

Convert to string:
>>>str(3.14159)
'3.14159'

>>>str(42)
'42'

You can also test to see what type you have. You do this by using the type() function call. Here are some examples.

>>>type('42')
<class 'str'>

>>>type(4.2)
<class 'float'>

As the class I am following online is using an older version of Python I'm trying to keep up with the new rules but I may (will) miss some. I started running them on the new one so I can learn it better and hopefully this will fix the discrepancies I've been having. Here is a site that has a lot of the new changes.

No comments:

Post a Comment