Python/CheatSheet
< Python
Variables
Tuples
- not changeable
a = (1,2,3) b = ("test", "with", "strings")
b[0] -> test
Lists
- changeable
c = [4,5,6] d = ["this", "is", "a", "list"]
d[0] -> this
d[0] = 'new' d[0:1] = ['new', 'stuff'] d.append('dude') d.count('new') del d[0:1] d.extend(['more', 'elements'] d.index(x) d.insert(i,x) d.pop() d.remove(x) d.reverse() d.sort()
Dictionaries
- mapping
e = {'size':5, 'color':'red', 'weight':100}
e['size'] -> 5
Operators
+ - * / // % ** & | < <= > >= != == is is not in not in and or
Flow Control
If Then Else
if x < 0: print('Negative') elif x == 0: print('Zero') else: print('More')
For loops
for x in ['cat', 'dog', 'bird']: print (x) for i in [1,2,3,4,5]: print (i+10)
While loops
while test: print (answer)
while True: print (answer) if answer == '2': break
x = 0 while x < 50: x = x+1
try ... except
try: result = x / y except ZeroDivisionError: print("division by zero!") else: print("result is", result) finally: print("executing finally clause")
Statements
assert break continue del exec global import nonlocal pass raise return yield
Strings
string = "Hello World" string = 'Hello World' string[4] # = 'o' string.split(' ') # ['Hello', 'World']
String functions
capitalize() center(width) count(sub,start,end) decode() encode() endswith(sub) expandtabs() find(sub,start,end) index(sub,start,end) isalnum() isalpha() isdigit() islower() isspace() istitle() isupper() join() ljust(width) lower() lstrip() partition(sep) replace(old,new) rfind(sub,start,end) rindex(sub,start,end) rjust(width) rpartition(sep) rsplit(sep) rstrip() split(sep) splitlines() startswith(sub) strip() swapcase() title() translate(table) upper() zfill(width)
Functions
datetime
today() now(timezoneinfo) utcnow() fromordinal(ordinal) combine(date,time) strptime(date,format) fromtimestamp(timestamp) utcfromtimestamp(timestamp)
time
replace() utcoffset() isoformat() __str__() dst() tzname() strftime(format)
strftime & strptime format
Input & Output
Escape sequences
ES | Note |
---|---|
\\ | backslash |
\' | ' |
\" | " |
\b | backspace |
\f | form feed |
\n | line feed |
\t | horizontal tab |
\v | vertical tab |
\N{Name} | Unicode by name |
\uxxxx | 16bit unicode |
\uxxxxxxxx | 32bit unicode |
\123 | ASCII code |
\xhh | Extended ASCII code (hex) |