Basic Data Types
Ref.: Python Built-in Types
Strings
Single quote
Example using single quotes:
>>> string_1 = 'using single quotes'
>>> string_2 = 'using single (')'
File "<stdin>", line 1
string_2 = 'using single (')'
^
SyntaxError: unmatched ')'
>>> string_2 = 'using single (\')'
Double quotes
Example using double quotes:
>>> string_3 = "using double quotes"
>>> string_4 = "using " quotes"
File "<stdin>", line 1
string_4 = "using " quotes"
^ SyntaxError: unterminated string literal (detected at line 1)
>>> string_4 = "using \" quotes"
Triple quotation
Example using triple quotes:
>>> string_5 = '''using triple single quotes'''
>>> string_6 = '''using triple ' '''
>>> string_7 = """using triple double quotes"""
>>> string_7 = """using triple " """
>>> string_8 = """using
... a
... multiline
... string
... handling '
... and ""
... """
String Formatting
3 ways to perform string formatting:
Using the modulo % character.
Using the .format() string method.
New method since Python 3.6: f-strings.
See:
Numeric
Python 2: int, long, float, complex
Python 3: int, float, complex
Integers
In Python 2 an int may be promoted to a long in Python 3 stays as int:
>>> n = 11
>>> type(n)
<type 'int'>
>>> n
11
>>> print(n)
11
Python 2:
>>> import sys
>>> sys.maxint
2147483647
Python 3:
>>> sys.maxint
Traceback (most recent call last):
File "<stdin>", line 1, in <module> AttributeError: module 'sys' has no
attribute 'maxint'
Python 2:
>>> n = 2147483647
>>> n = n + 1
>>> type(n)
<type 'long'>
>>> n
2147483648L
>>> print(n)
2147483648
>>> n = - sys.maxint - 1
-2147483648
>>> type(n)
<type 'int'>
Python 3:
>>> n = 1
>>> n
1
>>> type(n)
<class 'int'>
>>>
Floats
Python 2:
>>> f = 5.2
>>> type(f)
<type 'float'>
>>> print(f)
5.2
Python 3:
>>> f = 5.2
>>> type(f)
<type 'float'>
>>> print(f)
5.2
Python 2:
>>> f = 5/2
>>> type(f)
<type 'int'>
>>> f
2
Python 3:
>>> f = 5/2
>>> type(f)
<class 'float'>
>>> f
2.5
Complex
>>> z = 3 + 5.7j
>>> type(z)
<type 'complex'>
>>> z.real
3.0
>>> z.imag 5.7
Boolean
True, False
>>> type(True)
<type 'bool'>
>>> a = 1
>>> b = 2
>>> a == b
False
>>> a != b
True
>>> bool(0)
False
>>> bool(123)
True
>>> bool("")
False
>>> int(True)
1
>>> 5 + True
6
Python 2: note that True or False were not a keyword so it was possible to re-assign:
>>> True
True
>>> False
False
>>> True=False
>>> True
False
Python 3: expected behaviour
>>> True=False
File "<stdin>", line 1
SyntaxError: can't assign to keyword