Python/CheatSheet: Difference between revisions

From Wiki
No edit summary
mNo edit summary
 
(131 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 =
== Tuples ==
* not changeable
<blockquote>
<pre>
a = (1,2,3)
b = ("test", "with", "strings")
</pre>
</blockquote>
<blockquote>
<pre>
b[0]
-> test
</pre>
</blockquote>
== Lists ==
* changeable
<blockquote>
<pre>
c = [4,5,6]
d = ["this", "is", "a", "list"]
</pre>
</blockquote>
<blockquote>
<pre>
d[0]                            -> 'this'
</pre>
</blockquote>
<blockquote>
<pre>
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
</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>
</blockquote>
== Dictionaries ==
* mapping
<blockquote>
<pre>
e = {'size':5, 'color':'red', 'weight':100}
</pre>
</blockquote>
<blockquote>
<pre>
e['size']
-> 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>
</blockquote>
= Operators =
<blockquote>
<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 not
in
not in
and
or
not
##### bitwise operators #####
&        and
|        or
^        xor
~        not
<<
>>
</pre>
</blockquote>
= Flow Control =
== If Then Else ==
== If Then Else ==
<blockquote>
<blockquote>
Line 10: Line 241:
</pre>
</pre>
</blockquote>
</blockquote>


== For loops ==
== For loops ==
Line 16: Line 246:
<pre>
<pre>
for x in ['cat', 'dog', 'bird']:
for x in ['cat', 'dog', 'bird']:
     print (w)
     print (x)
</pre>
</blockquote>
<blockquote>
<pre>
for i in [1,2,3,4,5]:
    print (i+10)
</pre>
</blockquote>
<blockquote>
<pre>
for item in container:
    if search_something(item):
        print(item)            # Found it!
        break
else:
      not_found_in_container() # Didn't find anything..
</pre>
</blockquote>
<blockquote>
<pre>
for index, element in enumerate(newarticles):
    print(index, element)
</pre>
</blockquote>
 
== While loops ==
<blockquote>
<pre>
while test:
    print (answer)
</pre>
</blockquote>
 
<blockquote>
<pre>
while True:
    print (answer)
    if answer == '2':
        break
</pre>
</pre>
</blockquote>
</blockquote>


<blockquote>
<pre>
x = 0
while x < 50:
    x = x+1   
</pre>
</blockquote>


== try ... except ==
<blockquote>
<pre>
try:
    result = x / y
except ZeroDivisionError:
    print("division by zero!")
else:
    print("result is", result)
finally:
    print("executing finally clause")
</pre>
</blockquote>


= Statements =
<blockquote>
<pre>
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
</pre>
</blockquote>


= Strings =
<blockquote>
<pre>
string = "Hello World"
string = 'Hello World'
string = '''multiline
        string'''


string[4]                            # = 'o'
string[-1]                            # = 'd'
string[:-7]                          # = 'Hell'
string.split(' ')                    # ['Hello', 'World']
</pre>
</blockquote>


== String functions ==
<blockquote>
<blockquote>
<pre>
<pre>
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
</pre>
</pre>
</blockquote>
</blockquote>


= Input & Output =
<blockquote>
<pre>
x = input("input:")
</pre>
</blockquote>


<blockquote>
<pre>
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)))
</pre>
</blockquote>


<blockquote>
<blockquote>
<pre>
<pre>
import sys
sys.argv[0]                -> first command line argument
</pre>
</blockquote>


= Files =
<blockquote>
<pre>
file = open (ordersfile, 'rb')
file.read()
file.readline()
file.readlines()
file.close()
</pre>
</pre>
</blockquote>
</blockquote>


<blockquote>
<pre>
import pickle


with open(ordersfile, 'wb') as fp:
    pickle.dump(orders, fp)


with open (ordersfile, 'rb') as fp:
    orders = pickle.load(fp)
</pre>
</blockquote>


<blockquote>
<blockquote>
<pre>
<pre>
import os.path
os.path.exists(file_path)
</pre>
</blockquote>


= Escape sequences =
<blockquote>
{| class="wikitable"
|-
! 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)
|}
</blockquote>
= Double underscore variables =
* __file__
** path of script
<blockquote>
<pre>
import os
os.path.split(__file__)[0] + '/'
</pre>
</pre>
</blockquote>
</blockquote>
* __name__
** name of submodule or "__main__", if script is directly started


= 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>
<blockquote>
<pre>
<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>
</pre>
</blockquote>
</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 ==
<blockquote>
<pre>
today()
now(timezoneinfo)
utcnow()
fromordinal(ordinal)
combine(date,time)
strptime(date,format)
fromtimestamp(timestamp)
utcfromtimestamp(timestamp)
</pre>
</blockquote>
== import time ==
<blockquote>
<pre>
replace()
utcoffset()
isoformat()
__str__()
dst()
tzname()
strftime(format)
sleep()
</pre>
</blockquote>
== timeit ==
<blockquote>
<pre>
from timeit import default_timer as timer
start = timer()
do_something()
end = timer()
print(end-start)
</pre>
</blockquote>
== strftime & strptime format ==
<blockquote>
<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>
</blockquote>
== import os ==
<blockquote>
<pre>
with ignored(OSError):
    os.remove('somefile.tmp')
</pre>
</blockquote>
== sorted() ==
<blockquote>
<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>
</blockquote>
== other ==
<blockquote>
<pre>
iter
range
xrange
sorted()
sorted,x, reverse=True)
reversed()
</pre>
</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()