Skip to content

Latest commit

 

History

History
59 lines (45 loc) · 1.35 KB

File metadata and controls

59 lines (45 loc) · 1.35 KB

Python Language Overview

Datatypes

Common Python datatypes include:

Detection

Use the type() function to detect the datatype of any object:

type("Hello") #> <type 'str'>
type("100") #> <type 'str'>
type(100) #> <type 'int'>
type(0.45) #> <type 'float'>
type(True) #> <type 'bool'>
type(False) #> <type 'bool'>
type(None) #> <type 'NoneType'>
type({"a":1, "b":2, "c":3}) #> <type 'dict'>
type([1,2,3]) #> <type 'list'>

Alternatively call .__class__.__name__ on any object to detect its class name:

"Hello".__class__.__name__ #> 'str'
{"a":1, "b":2, "c":3}.__class__.__name__ #> 'dict'
[1,2,3].__class__.__name__ #> 'list'

Use the isinstance function when comparing datatypes:

isinstance("Hello", str) #> True
isinstance([1,2,3], list) #> True
isinstance([1,2,3], str) #> False

Conversion

Here are a few examples of how to convert between datatypes:

# convert strings to numbers:
int("500") #> 500
float("0.45") #> 0.45

# convert numbers to strings:
str(100) #> "100"
str(0.45) #> "0.45"