Python/CheatSheet: Difference between revisions
< Python
mNo edit summary |
|||
(85 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
{| class="wikitable" style="float:right; margin-left: 10px;" width="400px" | |||
| Other articles | |||
|- | |||
| | |||
* [[Python]] | |||
* [[Python/Pythonic Concepts]] | |||
* [[Python/Object Orientation]] | |||
* [[Python/decorators]] | |||
* [[Python/Jupyter]] | |||
* [[Python/Jupyter Installation]] | |||
* [[Python/pip]] | |||
* [[Python/requirements.txt]] | |||
* [[Python/venv]] | |||
* [[Python/Best Practices]] | |||
* [[Python/REST]] | |||
|- | |||
| Libraries | |||
|- | |||
| | |||
* [[Python/logging]] | |||
* [[Python/requests]] | |||
* [[Python/selenium]] | |||
* [[Python/flask]] | |||
* [[Python/pandas]] | |||
* [[Python/bokeh]] | |||
* [[Python/beautifulsoup]] | |||
* [[Python/pymysql]] | |||
* [[Python/SQLite]] | |||
* [[Python/feedparser]] | |||
* [[Python/Desktop Automation]] | |||
* [[Python/traceback]] | |||
|} | |||
= Python Shebang = | |||
<blockquote> | |||
<pre> | |||
#!/usr/bin/env python3 | |||
</pre> | |||
</blockquote> | |||
= Comments = | |||
<blockquote> | |||
<pre> | |||
# This is a comment | |||
print("Hello, World!") | |||
</pre> | |||
</blockquote> | |||
= Variables = | = Variables = | ||
== Tuples == | == Tuples == | ||
Line 27: | Line 75: | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
d[0] | d[0] -> 'this' | ||
-> this | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 34: | Line 81: | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
d[0] = ' | d[0] = 'this' | ||
d[0:1] = [' | d[0:1] = ['this', 'is'] | ||
d. | d[0:-1] = ['this', 'is', 'a'] | ||
d.count('new') | d.index(x) # Return index of the first item whose value is x | ||
len(d) # length | |||
d.extend(['more', 'elements'] | 'term' in d # find | ||
d. | d.count('new') # count number of 'new' | ||
d. | |||
d.pop() | d.append('dude') # add item to list | ||
d. | d.extend(['more', 'elements'] # Extend the list by appending all the items from the iterable | ||
d.reverse() | d.insert(i,x) # Insert an item at a given position | ||
d.sort() | |||
del d[0:1] # remove item at given index | |||
d.remove(x) # Remove the first item from the list whose value is x | |||
d.pop() # Remove the item at the given position in the list | |||
d.clear() # remove all items | |||
d.reverse() # reverse elements in place | |||
d.sort(key=None, reverse=False) # sort the items of the list | |||
</pre> | |||
</blockquote> | |||
* [[#sorted()]] | |||
== List Comprehension == | |||
<blockquote> | |||
<pre> | |||
[expression for item in list (if condition)] | |||
[x*5 for x in range(5)] -> [0, 5, 10, 15, 20] | |||
[x for x in range(5) if x%2 == 0] -> [0, 2, 4] | |||
[i*i for i in range(5)] -> [0, 1, 4, 9, 16] | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
[ x for x in books if (x['language'] == "de"] # filter | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 61: | Line 137: | ||
e['size'] | e['size'] | ||
-> 5 | -> 5 | ||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
keys = ['a', 'b', 'c'] | |||
values = [1, 2, 3] | |||
dictionary = dict(zip(keys, values)) | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
for k, v in e.items(): | |||
print (k, v) | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
e[k] | |||
e[k] = x | |||
e.clear() | |||
e.copy() | |||
del e[k] | |||
e.get(k,x) | |||
k in e | |||
k not in e | |||
e.items() | |||
e.keys() | |||
e.popitem() | |||
e.setdefault() | |||
e1.update(e2) | |||
e.values() | |||
</pre> | |||
</blockquote> | |||
import copy | |||
new_dict = copy.deepcopy(old_dict) | |||
== Assigning values == | |||
<blockquote> | |||
<pre> | |||
x = 1 | |||
first, second, third = sequence | |||
x, y = 0, 1 | |||
x, y = y, x+y | |||
x, _, y = (1, 2, 3) | |||
y += 1 | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 67: | Line 193: | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
+ | ##### arithmetic operators ##### | ||
- | + addition | ||
* | - subtraction | ||
/ | * multiplication | ||
/ division | |||
% | % modulus | ||
** | ** exponentiation | ||
// floor division | |||
##### comparison operators ##### | |||
== equal | |||
!= not equal | |||
< less than | |||
<= less than or equal to | |||
> greater than | |||
>= greater than or equal to | |||
is | is | ||
is not | is not | ||
in | in | ||
not in | not in | ||
and | and | ||
or | or | ||
not | |||
##### bitwise operators ##### | |||
& and | |||
| or | |||
^ xor | |||
~ not | |||
<< | |||
>> | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 111: | Line 247: | ||
for x in ['cat', 'dog', 'bird']: | for x in ['cat', 'dog', 'bird']: | ||
print (x) | print (x) | ||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
for i in [1,2,3,4,5]: | for i in [1,2,3,4,5]: | ||
print (i+10) | print (i+10) | ||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
for item in container: | for item in container: | ||
if search_something(item): | if search_something(item): | ||
# Found it! | print(item) # Found it! | ||
break | break | ||
else: | else: | ||
not_found_in_container() # Didn't find anything.. | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
for index, element in enumerate(newarticles): | |||
print(index, element) | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 168: | Line 314: | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
assert | assert # for debugging, will raise AssertionError if 'assert [false]' | ||
break | break # break out of for or while loop | ||
continue | continue # end current iteration in a for or while loop | ||
nonlocal | nonlocal | ||
pass | pass # placeholder for future code | ||
raise | raise # raise exception | ||
return | return | ||
yield | yield | ||
</pre> | </pre> | ||
Line 188: | Line 330: | ||
string = "Hello World" | string = "Hello World" | ||
string = 'Hello World' | string = 'Hello World' | ||
string = '''multiline | |||
string''' | |||
string[4] # = 'o' | string[4] # = 'o' | ||
string[-1] # = 'd' | |||
string[:-7] # = 'Hell' | |||
string.split(' ') # ['Hello', 'World'] | string.split(' ') # ['Hello', 'World'] | ||
</pre> | </pre> | ||
Line 216: | Line 362: | ||
ljust(width) | ljust(width) | ||
lower() | lower() | ||
partition(sep) | partition(sep) | ||
replace(old,new) | replace(old,new) # replace old string with new string | ||
replace(" ","") # remove all spaces | |||
rfind(sub,start,end) | rfind(sub,start,end) | ||
rindex(sub,start,end) | rindex(sub,start,end) | ||
Line 224: | Line 370: | ||
rpartition(sep) | rpartition(sep) | ||
rsplit(sep) | rsplit(sep) | ||
split(sep) | split(sep) | ||
splitlines() | splitlines() | ||
startswith(sub) | startswith(sub) | ||
strip() | strip() #remove leading and trailing whitespaces | ||
rstrip() | |||
lstrip() | |||
swapcase() | swapcase() | ||
title() | title() | ||
Line 234: | Line 382: | ||
upper() | upper() | ||
zfill(width) | zfill(width) | ||
''.join(e for e in string if e.isalnum()) # remove all special chars in string | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 258: | Line 408: | ||
<pre> | <pre> | ||
import sys | import sys | ||
sys.argv[ | sys.argv[0] -> first command line argument | ||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 268: | Line 418: | ||
file.read() | file.read() | ||
file.readline() | file.readline() | ||
file.readlines() | |||
file.close() | file.close() | ||
</pre> | </pre> | ||
Line 281: | Line 432: | ||
with open (ordersfile, 'rb') as fp: | with open (ordersfile, 'rb') as fp: | ||
orders = pickle.load(fp) | orders = pickle.load(fp) | ||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
import os.path | |||
os.path.exists(file_path) | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
Line 317: | Line 475: | ||
|} | |} | ||
</blockquote> | </blockquote> | ||
= Double underscore variables = | |||
* __file__ | |||
** path of script | |||
<blockquote> | |||
<pre> | |||
import os | |||
os.path.split(__file__)[0] + '/' | |||
</pre> | |||
</blockquote> | |||
* __name__ | |||
** name of submodule or "__main__", if script is directly started | |||
= Functions = | = Functions = | ||
== User Defined Functions == | |||
<blockquote> | |||
<pre> | |||
def userfunction(): | |||
print("Hello") | |||
userfunction() | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
def userfunction(variable): | |||
print("Hello", variable) | |||
userfunction('Peter') | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
def userfunction(variable): | |||
print("Hello", variable) | |||
test = 2 | |||
return test | |||
print(userfunction('Peter')) # prints "2" | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
def userfunction(variable1, variable2 = "John"): | |||
print("Hello", variable1, variable2) | |||
userfunction("dear") | |||
</pre> | |||
</blockquote> | |||
<blockquote> | |||
<pre> | |||
def userfunction(*variables): | |||
for var in variables: | |||
print(var) | |||
userfunction(1,2,3,4) | |||
</pre> | |||
</blockquote> | |||
== Lambda == | |||
small function, with any number of arguments | |||
<blockquote> | |||
<pre> | |||
x = lambda a : a + 10 | |||
print(x(5)) | |||
x = lambda a, b : a * b | |||
print(x(5, 6)) | |||
(lambda x, y: x + y)(2, 3) | |||
5 | |||
</pre> | |||
</blockquote> | |||
== import datetime == | == import datetime == | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
Line 348: | Line 581: | ||
</blockquote> | </blockquote> | ||
== | == timeit == | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
from timeit import default_timer as timer | |||
start = timer() | |||
do_something() | |||
end = timer() | |||
print(end-start) | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
== strftime & strptime format == | |||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE) | |||
%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE) | |||
%w Weekday as a decimal number. Sundy=0 0, 1, …, 6 | |||
%d Day of the month, zero-padded 01, 02, …, 31 | |||
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE) | |||
%B Month as locale’s full name. January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE) | |||
%m Month as a zero-padded decimal number. 01, 02, …, 12 | |||
%y Year without century, zero-padded 00, 01, …, 99 | |||
%Y Year with century as a decimal number. 0001, 0002, …, 2013, 2014, …, 9998, 9999 | |||
%H Hour (24-hour clock), zero-padded 00, 01, …, 23 | |||
%I Hour (12-hour clock), zero-padded 01, 02, …, 12 | |||
%p Locale’s equivalent of either AM or PM. AM, PM (en_US);am, pm (de_DE) | |||
%M Minute, zero-padded 00, 01, …, 59 | |||
%S Second,zero-padded 00, 01, …, 59 | |||
%f Microsecond, zero-padded 000000, 000001, …, 999999 | |||
%z UTC offset in the form ±HHMM[SS[.ffffff]] (empty), +0000, -0400, +1030, +063415, -030712.345216 | |||
%Z Time zone name (empty if none) (empty), UTC, EST, CST | |||
%j Day of the year, zero-padded 001, 002, …, 366 | |||
%U Week number, Sunday first day of week 00, 01, …, 53 | |||
%W Week number, Monday first day of week 00, 01, …, 53 | |||
%c Locale’s appropriate date and time Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE) | |||
%x Locale’s appropriate date 08/16/88 (None); 08/16/1988 (en_US); 16.08.1988 (de_DE) | |||
%X Locale’s appropriate time 21:30:00 (en_US); 21:30:00 (de_DE) | |||
%% A literal '%' character. % | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
== import os == | |||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
with ignored(OSError): | |||
os.remove('somefile.tmp') | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
== sorted() == | |||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
sorted([5, 2, 3, 1, 4]) -> [1, 2, 3, 4, 5] | |||
sorted("This is a test string".split(), key=str.lower) -> ['a', 'is', 'string', 'test', 'This'] | |||
user_tuples = [('john', 15),('jane', 12),('dave', 10)] | |||
sorted(user_tuples, key=lambda user: user[1]) -> [('dave', 10), ('jane', 12), ('john', 15)] | |||
books_sorted = sorted(books_with_review, key=lambda k: k['amz-num'], reverse=True) | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
== | == other == | ||
<blockquote> | <blockquote> | ||
<pre> | <pre> | ||
iter | |||
range | |||
xrange | |||
sorted() | |||
sorted,x, reverse=True) | |||
reversed() | |||
</pre> | </pre> | ||
</blockquote> | </blockquote> | ||
[[Category:Programming]] |
Latest revision as of 15:13, 28 September 2024
Other articles |
Libraries |
Python Shebang
#!/usr/bin/env python3
Comments
# This is a comment print("Hello, World!")
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] = 'this' d[0:1] = ['this', 'is'] d[0:-1] = ['this', 'is', 'a'] d.index(x) # Return index of the first item whose value is x len(d) # length 'term' in d # find d.count('new') # count number of 'new' d.append('dude') # add item to list d.extend(['more', 'elements'] # Extend the list by appending all the items from the iterable d.insert(i,x) # Insert an item at a given position del d[0:1] # remove item at given index d.remove(x) # Remove the first item from the list whose value is x d.pop() # Remove the item at the given position in the list d.clear() # remove all items d.reverse() # reverse elements in place d.sort(key=None, reverse=False) # sort the items of the list
List Comprehension
[expression for item in list (if condition)] [x*5 for x in range(5)] -> [0, 5, 10, 15, 20] [x for x in range(5) if x%2 == 0] -> [0, 2, 4] [i*i for i in range(5)] -> [0, 1, 4, 9, 16]
[ x for x in books if (x['language'] == "de"] # filter
Dictionaries
- mapping
e = {'size':5, 'color':'red', 'weight':100}
e['size'] -> 5
keys = ['a', 'b', 'c'] values = [1, 2, 3] dictionary = dict(zip(keys, values))
for k, v in e.items(): print (k, v)
e[k] e[k] = x e.clear() e.copy() del e[k] e.get(k,x) k in e k not in e e.items() e.keys() e.popitem() e.setdefault() e1.update(e2) e.values()
import copy
new_dict = copy.deepcopy(old_dict)
Assigning values
x = 1 first, second, third = sequence x, y = 0, 1 x, y = y, x+y x, _, y = (1, 2, 3) y += 1
Operators
##### arithmetic operators ##### + addition - subtraction * multiplication / division % modulus ** exponentiation // floor division ##### comparison operators ##### == equal != not equal < less than <= less than or equal to > greater than >= greater than or equal to is is not in not in and or not ##### bitwise operators ##### & and | or ^ xor ~ not << >>
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)
for item in container: if search_something(item): print(item) # Found it! break else: not_found_in_container() # Didn't find anything..
for index, element in enumerate(newarticles): print(index, element)
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 # for debugging, will raise AssertionError if 'assert [false]' break # break out of for or while loop continue # end current iteration in a for or while loop nonlocal pass # placeholder for future code raise # raise exception return yield
Strings
string = "Hello World" string = 'Hello World' string = '''multiline string''' string[4] # = 'o' string[-1] # = 'd' string[:-7] # = 'Hell' 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() partition(sep) replace(old,new) # replace old string with new string replace(" ","") # remove all spaces rfind(sub,start,end) rindex(sub,start,end) rjust(width) rpartition(sep) rsplit(sep) split(sep) splitlines() startswith(sub) strip() #remove leading and trailing whitespaces rstrip() lstrip() swapcase() title() translate(table) upper() zfill(width) ''.join(e for e in string if e.isalnum()) # remove all special chars in string
Input & Output
x = input("input:")
print(x+12) print("Hello world") print("Integer: %i, Float: %6.2f" % (123, 12.043)) print("Integer: {intvar:i}, Float: {floatvar:.2f}") print("value of x: {0:05d}".format(x)) print("%3i%6s" % (i, chr(i)))
import sys sys.argv[0] -> first command line argument
Files
file = open (ordersfile, 'rb') file.read() file.readline() file.readlines() file.close()
import pickle with open(ordersfile, 'wb') as fp: pickle.dump(orders, fp) with open (ordersfile, 'rb') as fp: orders = pickle.load(fp)
import os.path os.path.exists(file_path)
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)
Double underscore variables
- __file__
- path of script
import os os.path.split(__file__)[0] + '/'
- __name__
- name of submodule or "__main__", if script is directly started
Functions
User Defined Functions
def userfunction(): print("Hello") userfunction()
def userfunction(variable): print("Hello", variable) userfunction('Peter')
def userfunction(variable): print("Hello", variable) test = 2 return test print(userfunction('Peter')) # prints "2"
def userfunction(variable1, variable2 = "John"): print("Hello", variable1, variable2) userfunction("dear")
def userfunction(*variables): for var in variables: print(var) userfunction(1,2,3,4)
Lambda
small function, with any number of arguments
x = lambda a : a + 10 print(x(5)) x = lambda a, b : a * b print(x(5, 6)) (lambda x, y: x + y)(2, 3) 5
import datetime
today() now(timezoneinfo) utcnow() fromordinal(ordinal) combine(date,time) strptime(date,format) fromtimestamp(timestamp) utcfromtimestamp(timestamp)
import time
replace() utcoffset() isoformat() __str__() dst() tzname() strftime(format) sleep()
timeit
from timeit import default_timer as timer start = timer() do_something() end = timer() print(end-start)
strftime & strptime format
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE) %A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE) %w Weekday as a decimal number. Sundy=0 0, 1, …, 6 %d Day of the month, zero-padded 01, 02, …, 31 %b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE) %B Month as locale’s full name. January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE) %m Month as a zero-padded decimal number. 01, 02, …, 12 %y Year without century, zero-padded 00, 01, …, 99 %Y Year with century as a decimal number. 0001, 0002, …, 2013, 2014, …, 9998, 9999 %H Hour (24-hour clock), zero-padded 00, 01, …, 23 %I Hour (12-hour clock), zero-padded 01, 02, …, 12 %p Locale’s equivalent of either AM or PM. AM, PM (en_US);am, pm (de_DE) %M Minute, zero-padded 00, 01, …, 59 %S Second,zero-padded 00, 01, …, 59 %f Microsecond, zero-padded 000000, 000001, …, 999999 %z UTC offset in the form ±HHMM[SS[.ffffff]] (empty), +0000, -0400, +1030, +063415, -030712.345216 %Z Time zone name (empty if none) (empty), UTC, EST, CST %j Day of the year, zero-padded 001, 002, …, 366 %U Week number, Sunday first day of week 00, 01, …, 53 %W Week number, Monday first day of week 00, 01, …, 53 %c Locale’s appropriate date and time Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE) %x Locale’s appropriate date 08/16/88 (None); 08/16/1988 (en_US); 16.08.1988 (de_DE) %X Locale’s appropriate time 21:30:00 (en_US); 21:30:00 (de_DE) %% A literal '%' character. %
import os
with ignored(OSError): os.remove('somefile.tmp')
sorted()
sorted([5, 2, 3, 1, 4]) -> [1, 2, 3, 4, 5] sorted("This is a test string".split(), key=str.lower) -> ['a', 'is', 'string', 'test', 'This'] user_tuples = [('john', 15),('jane', 12),('dave', 10)] sorted(user_tuples, key=lambda user: user[1]) -> [('dave', 10), ('jane', 12), ('john', 15)] books_sorted = sorted(books_with_review, key=lambda k: k['amz-num'], reverse=True)
other
iter range xrange sorted() sorted,x, reverse=True) reversed()