>>> 1 + 2
3
>>> 1 - 2
-1
>>> 1 * 2
2
>>> 4 / 2
2
In Python 2, division of two integers is an integer
>>> 3/2 1
In Python 3, division of two integers is a float
>>> 3/2 1.5
To get a float result in Python 2, make one number a float
>>> float(3) / 2 1.5
To get Python 3 behavior in Python 2
from __future__ import division
>>> 1 // float(2)
0.0
>>> float(3) // 2
1.0
>>> 1 % 2
1
>>> 7 % 5
2
>>> divmod(1, 2)
(0, 1)
>>> divmod(7, 5)
(1, 2)
>>> 2 ** 2 + 10 / 2
9
>>> 2 ** (2 + 10) / 2
2048
Functions and lookups are completed before operations
>>> 2 * abs(-2) 4
Equal (==)
>>> 1 == 1 True >>> "morning" == "night" False
Not Equal (!=)
>>> 1 != 1 False >>> "morning" != "night" True
Less than (<)
>>> 1 < 2 True
Less than or equal (<=)
>>> 2 <= 2 True
Greater than (>)
>>> 2 > 1 True
Greater than or equal (>=)
>>> 2 >= 2 True
Identity (is / is not)
>>> 1 is 1 True >>> [1, 2] is [1, 2] False >>> 1 is not 1 False >>> [1, 2] is not [1, 2] True
is
tests if two objects are the same, not if they have the same value
>>> False or False
False
>>> False or True
True
>>> True and True
True
>>> True and False
False
>>> not True
False
>>> not False
True
Union - Create new set with elements from all sets
>>> set([1, 2]) | set([2, 3]) | set([2, 3, 4]) set([1, 2, 3, 4])
Intersection - Create new set with elements common to all sets
>>> set([1, 2]) & set([2, 3]) & set([2, 3, 4]) set([2])
Difference - New set with elements appearing only in first set
>>> set([1, 2]) - set([2, 3, 4]) set([1])
Symmetric Difference - New set with unique elements from each set
>>> set([1, 2]) ^ set([2, 3, 4]) set([1, 3, 4])
Subset - True if every element in first set is in second set
>>> set([1, 2, 3]) <= set([1, 2, 3, 4]) True
Proper Subset - True if subset and sets are not equal
>>> set([1, 2, 3, 4]) < set([1, 2, 3, 4]) False
Superset - True if every element in second set is in first set
>>> set([1, 2, 3, 4]) >= set([1, 2, 3]) True
Proper Superset - True if superset and not equal
>>> set([1, 2, 3, 4]) > set([1, 2, 3, 4]) False
The basic assignment operator is the equal sign
>>> var1 = 2
There is an assignment shortcut for basic math operators
>>> var1 = 2 >>> var1 += 1 >>> var1 3 >>> var2 = 7 >>> var2 %= 5 >>> var2 2
For sequences, concatenation and assignment can be combined
>>> mylist = [1, 2] >>> mylist += [3, 4] >>> mylist [1, 2, 3, 4]
Works for set operations too
>>> mySet = set([1, 2, 3]) >>> mySet ^= set([2, 3, 4]) >>> mySet set([1, 4])
__repr__()
methodrepr()
function or in the Python console__str__()
methodstr()
function or when treating a non-string object as a stringThe %
operator can be used to format strings
The format is similar to sprintf()
in C
Values can be specified in a tuple or dictionary
>>> "Hi! My name is %s. I can count to %d" % ('George', 732) 'Hi! My name is George. I can count to 732' >>> "Hi! My name is %(name)s. I can count to %(number)d" % \ ... {'name' : 'George', 'number' : 732} 'Hi! My name is George. I can count to 732'
Single values can be on their own
>>> 'Hello, %s' % 'world' 'Hello, world'
#
– “Alternate form” (non-decimal numbers have prefix)0
– Pad number with 0’s-
– Adjust left(space)
– Space before positive number+
– ‘+’ or ‘-‘ before numberd
or i
– Signed integer (decimal)o
– Signed integer (octal)x
or X
– Signed integer (hex)e
or E
– Float in exponential formatf
or F
– Float in decimal formatg
or G
– Float in decimal or exponential depending on sizec
– Single character (converts positive integer)r
– Python object converted with repr()
s
– Python object converted with str()
Pad integer with zeros
>>> '%03d' % 12 '012'
Float precision to 3 decimals
>>> '%.3f' % 12.1236 '12.124'
Float precision as a variable
>>> '%.*f' % (3, 12.1236) '12.124'
Left pad string to 15 characters
>>> '%15s' % 'hello' ' hello'
Right pad string to 15 characters
>>> '%-15s' % 'hello' 'hello '
Print representation string for an object
>>> '%r' % Exception("something bad Happened") "Exception('something bad Happened',)"
In Python 2.6, the str.format()
method was introduced
Preferred method in newer versions of Python
More flexible than the old format
By default, objects are converted using their own __format__()
method
Falls back to str()
and then repr()
>>> # In Python 2.7+, no name or index is required ... "Hi! My name is {}. I can count to {}".format('George', 732) 'Hi! My name is George. I can count to 732' >>> "Hi! My name is {1}. I can count to {0}".format(732, 'George') 'Hi! My name is George. I can count to 732' >>> "Hi! My name is {name}. I can count to {number}".format( ... name='George', number=732) 'Hi! My name is George. I can count to 732'
datetime.datetime
for an object with special formatting<
– Left-aligned (default for most objects)>
– Right-aligned (default for numbers)=
– Force padding after any sign for numbers^
– Center is available space+
– Include sign for both positive and negative numbers-
– Include sign only for negative numbers (default)(space)
– Include a space for positive numbers and sign for negative numbersb
– Integer (binary)n
– Same as ‘d’ or ‘g’, but use locale to determine separator%
– Float as a percentagePad integer with zeros
>>> '{:03d}'.format(12) '012'
Float precision to 3 decimals
>>> '{:.3f}'.format(12.1236) '12.124'
Float precision as a variable
>>> '{1:.{0}f}'.format(3, 12.1236) '12.124'
Left pad string to 15 characters
>>> '{:>15}'.format('hello') ' hello'
Right pad string to 15 characters
>>> '{:<15}'.format('hello') 'hello
Print representation string for an object
>>> '{!r}'.format(Exception("something bad Happened")) "Exception('something bad Happened',)"
Center within 15 characters with underscores
>>> '{:_^15}'.format('hello') '_____hello_____'
Print as a percentage to two decimal places
>>> '{:.2%}'.format(0.56) '56.00%'
Perform multiple substitutions with the same value
>>> '{0}-di, {0}-da'.format('ob-la') 'ob-la-di, ob-la-da'
Introduced in Python 3.6
Allow expressions to be embedded in strings
Faster than other formatting options
No backslashes in expressions (OK in string)
No comments in expressions
Curly braces are escaped with more curly braces
>>> name = 'George' >>> limit = 732 >>> f"Hi! My name is {name}. I can count to {max(10, limit)}" 'Hi! My name is George. I can count to 732'
datetime.datetime
for an object with special formattingRaw f strings can be created by prepending fr
>>> interpreted = 'Nope' >>> fr'I\'m not interpreted? {interpreted}' "I\\'m not interpreted? Nope"
end
value:step
is optionalBasic slice
>>> myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> myList[2:5] [2, 3, 4] >>> myList[4:] [4, 5, 6, 7, 8, 9] >>> myList[-3:] [7, 8, 9] >>> myList[:4] [0, 1, 2, 3] >>> myList[:] # Creates a shallow copy of a list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Extended Slice
>>> myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> myList[2:8:2] [2, 4, 6] >>> myList[::-3] [9, 6, 3, 0]
>>> myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del myList[::2]
>>> myList
[1, 3, 5, 7, 9]
>>> myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> del myList[:] # Clear a list
>>> myList
[]
>>> myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> myList[3:5] = ['A', 'B']
>>> myList
[0, 1, 2, 'A', 'B', 5, 6, 7, 8, 9]
zip()
creates a list of tuples with an element from each iterableSyntax: zip([iterable, …])
>>> input1 = [1, 2 , 3, 4, 5, 6] >>> input2 = [2, 4, 6, 8, 10] >>> zip(input1, input2) [(1, 2), (2, 4), (3, 6), (4, 8), (5, 10)]
copy()
method>>> myDict = {'aList' : [1, 2]}
>>> newDict = myDict.copy()
>>> newDict['aList'].append(3)
>>> myDict['aList']
[1, 2, 3]
To copy an object and it’s contents, use deepcopy()
from the copy
module
>>> import copy >>> myDict = {'aList' : [1, 2]} >>> newDict = copy.deepcopy(myDict) >>> newDict['aList'].append(3) >>> myDict['aList'] [1, 2]