1.23 | 3.14e-10 | 4E210 | 4.0e+210 |
454 | -17 | 023 (Octal) | 0xffff (hexidecimal) |
3-7j | 3.6+2.1j | 5J |
Operators (in descending precedence) | Description |
(...), [...], {...}, `...` | Tuple, list, dictionary, conversion to string |
x[i], x[i:j], x.y, x(...) | Indexing, slicing, qualification, function call |
-x, +x, ~x | Unary negation, unary identity, bitwise complement |
x * y, x / y, x % y | multiplication, division, remainder or format |
x + y, x - y | addition or concatenation, subtraction |
x << y, x >> y | Shift left y bits, shift right y bits |
x & y | Bitwise and |
x ^ y | Bitwise exclusive or |
x | y | Bitwise or |
<, <=, >, >=, <>, !=, is, is not, in, not in |
Comparison operators, identity tests, sequence membership |
not x | logical negation |
x and y | Logical and (with shortcut evaluation) |
x or y | Logical or (with shortcut evaluation) |
lambda args: expression | anonymous function |
When arithmetic is performed on mixed-type operands, e.g. 3.14 * 3, Python converts the simpler type to the more complex type. In this case, a copy of the 3 is converted to 3.00, then double arithmetic is performed, and the result is a double, 9.42.
Note that the operators +, *, and % are overloaded.
String Example | Explanation |
---|---|
'This is a "string."' | Strings may be enclosed in apostrophes. |
"This is today's second string." | Strings may be enclosed in quotation marks. |
"""This is a multiline string.""" | Strings enclosed in triple quotation marks may span several lines. |
"A" | There is no char type; for characters, use a single-character string. |
'' or "" | The empty string. |
Strings are immutable. You cannot modify a string.
Instead, slice the string and recombine, creating a new string.
Operation | Explanation |
---|---|
str1 + str2 | Concatenation |
str * 5 | Repetition |
str[i] | Indexing. (Counts from zero. Negative index counts from right end.) |
str[i:j] | Slicing. (From ith element to just before the jth) (The subscripts actually indicate the slice points, not the string elements.) |
len(str) | String length |
"There were %d sparrows and %d crows left." % (sparrow_ct, crow_ct) | String formatting |
for char in str: | Iteration through a string's members |
"C" in str | String membership |
Code | Description |
---|---|
%s | String |
%d | Decimal (int) |
%i | Integer |
%u | Unsigned (int) |
%O | Octal integer |
%x | Hex integer |
%e | Floating point scientific notation |
%f | Decimal (float) |
%% | Literal % |
Code | Meaning |
---|---|
\newline | Ignore newline |
\\ | Backslash |
\' | Apostrophe |
\" | Quotation mark |
\a | Bell ("alarm") |
\b | Backspace |
\e | Escape |
\000 | Null (Don't use to end a string in Python!) |
\n | Newline (linefeed) |
\v | Vertical tab |
\t | Tab (horizontal) |
\r | Carriage return |
\f | Formfeed |
\0XX | Octal value XX |
\xXX | Hex value XX |
\other | Any other character |
Also note: Many useful string functions are contained in the string module.
Operation | Interpretation |
---|---|
li1 = [ ] | Assigning an empty list |
li2 = [14, 22, -8, 0] | Assigning a list of 4 items. |
li3 = [4, "xyz", [4-5j, 0] ] | Nested lists |
lis[i], lis1[j][k] | Indexing a list |
lis[i:j] | Slicing a list |
len(lis1) | Length of a list |
lis1 + lis2 | Concatenate lists |
lis * 4 | Repeat a list |
for x in lis: | Iterate through a list |
x in lis | List membership |
lis.append(item) | Append item to list. |
lis.sort() | Sort list. |
lis.index(5) | Search for index of 5 in lis. |
lis.reverse() | Reverse elements of lis. |
del lis[5] | Remove lis[5] from list. |
lis[5:9] = [ ] | Remove 5th through 8th elements from lis. |
lis[k] = 7 | Assignment by index |
lis[j:k] = [4, 5, 6] | Assignment by slice |
range(5) | Returns list [0, 1, 2, 3, 4] |
range(4, 7) | Returns list [4, 5, 6] |
Dictionaries are similar to lists, except, instead of subscripts, dictionaries use keys.
Operation | Interpretation |
---|---|
{ } | Empty dictionary |
dic1 = {'spam':5, 'eggs':10} | Two-item dictionary. 'spam' and 'eggs' are the keys. |
dic2 = {'food': {'ham':1, 'egg':2}} | Nested dictionaries |
dic1['spam'], dic2['food']['egg'] | Indexing by key |
dic1.has_key('eggs') | Membership test method |
dic1.keys() | Method returns list of keys. |
dic1.values() | Method returns list of values. |
len(dic2) | Returns number of elements of dic2. |
dic3[key] = value | Changes element of dic3. |
del dic3[key] | Deletes an element from dic3. |
Tuples are, in effect, immutable lists. Thus, accessing data within tuples is fast, but changes require creation of new tuples.
Operation | Interpretation |
---|---|
( ) | An empty tuple |
tup1 = (4,) | A one-item tuple. The comma distinguishes it from a numerical expression. |
tup2 = (0, 1, 2, 4) | A four-item tuple |
tup2 = 0, 1, 2, 4 | Another four-item tuple |
tup3 = ('the', ('and', 'you')) | Nested tuples |
tup1[2], tup3[j][k] | Indexing |
tup2[2:4] | Slicing |
len(tup2) | Length |
tup1 + tup2 | Concatenation |
tup2 * 3 | Repetition |
for item in tup2: | Iteration through a tuple |
4 in tup2 | Membership |
Operation | Interpretation |
---|---|
output = open('/tmp/spam', 'w') | Create output file object, for writing file /tmp/spam. |
input = open('foo', 'r') | Create input file object, for reading file foo. |
big_str = input.read( ) | Read entire input file into big_str. |
str = input.read(N) | Read N bytes from input into str. |
str = input.readline() | Read next line (through end-of-line marker) into str. |
str_list = input.readlines() | Read entire file into a list of strings. |
output.write(str) | Write string str onto file. |
output.writelines(str_list) | Write all strings in str_list onto file. |
output.close() | Manual close of file. Close is also done automatically when file object goes out of scope (when collected). |
Python variables are references to stuff. Several variables may refer to the same object.
Assignment creates references, not copies.
Zero is False, non-zero is true. Any empty data structure is False; a non-empty structure is True. None is a null data structure, and is False.
Object | Value |
---|---|
"bar" | True |
"" | False |
[ ] | False |
{ } | False |
1 | True |
0.0 | False |
none | False |