|
On this page: type(), str(), int(), float(), list(), and tuple()
Data Types in Python, tuple
Python has many built-in data types. You have seen: int (integer), float (floating-point number), str (string), list (list), and dict (dictionary). They all have distinct representations:
|
>>> 'hello'
'hello'
>>> 256
256
>>> 1.99
1.99
>>> [1,2,3,4]
[1, 2, 3, 4]
>>> {'a':'apple', 'b':'banana', 'c':'carrot'}
{'a': 'apple', 'c': 'carrot', 'b': 'banana'}
| |
Let me introduce here another important data type, which is called tuple. A tuple is just like a list except it is fixed (i.e., immutable). It is marked with a pair of parentheses ( ), with each item separated by a comma ,. In fact, parentheses are not necessary but commas are, as seen in the bottom example.
|
>>> ('gold', 'silver', 'bronze')
('gold', 'silver', 'bronze')
>>> 1, 2, 3
(1, 2, 3)
| |
Displaying object type with type()
If you are ever unsure of the type of the particular object, you can use the type() function:
|
>>> type('hello')
<type 'str'>
>>> type(256)
<type 'int'>
>>> type('256')
<type 'str'>
| |
Converting Between Types
Many Python functions are sensitive to the type of data. For example, you cannot concatenate a string with an integer:
|
>>> age = 21
>>> sign = 'You must be ' + age + '-years-old to enter this bar'
Traceback (most recent call last):
File "<pyshell#71>", line 1, in <module>
sign = 'You must be ' + age + '-years-old to enter this bar'
TypeError: cannot concatenate 'str' and 'int' objects
| |
Therefore, you will often find yourself needing to convert one data type to another. Luckily, conversion functions are easy to remember: the type names double up as a conversion function. Thus, str() is the function that converts an integer, a list, etc. to a string, and list() is the function that converts something into the list type. For the example above, you would need the str() conversion function:
|
>>> age = 21
>>> sign = 'You must be ' + str(age) + '-years-old to enter this bar'
>>> sign
'You must be 21-years-old to enter this bar'
| |
Conversion Functions
Below is a table of the conversion functions in Python and their examples.
Function |
Converting what to what |
Example |
int() |
string, floating point → integer |
>>> int('2014')
2014
>>> int(3.141592)
3
|
float() |
string, integer → floating point number |
>>> float('1.99')
1.99
>>> float(5)
5.0
|
str() |
integer, float, list, tuple, dictionary → string |
>>> str(3.141592)
'3.141592'
>>> str([1,2,3,4])
'[1, 2, 3, 4]'
|
list() |
string, tuple, dictionary → list |
>>> list('Mary')
['M', 'a', 'r', 'y']
>>> list((1,2,3,4))
[1, 2, 3, 4]
|
tuple() |
string, list → tuple |
>>> tuple('Mary')
('M', 'a', 'r', 'y')
>>> tuple([1,2,3,4])
(1, 2, 3, 4)
|
|