Python/CheatSheet: Difference between revisions

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

Revision as of 22:08, 23 February 2018

Other articles

Python Shebang

#!/usr/bin/env python3

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')               # add item to list
d.count('new')
del d[0:1]
d.extend(['more', 'elements']    # Extend the list by appending all the items from the iterable
d.index(x)                       # Return index of the first item whose value is x
d.insert(i,x)                    # Insert an item at a given position
d.pop()                          # Remove the item at the given position in the list
d.remove(x)                      # Remove the first item from the list whose value is x
d.reverse()                      # reverse elements in place
d.sort(key=None, reverse=False)  # sort the items of the list
d.clear()                        # remove all items

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()

Assigning values

x = 1
first, second, third = sequence
x, y = 0, 1
x, y = y, x+y
y += 1

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)
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
break
continue
del
exec
global
import
nonlocal
pass
raise
return
yield

Strings

string = "Hello World"
string = 'Hello World'
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()
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)

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[1]

Files

file = open (ordersfile, 'rb')
file.read()
file.readline()
file.close()
import pickle

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

with open (ordersfile, 'rb') as fp:
    orders = pickle.load(fp)

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)

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)

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()

strftime & strptime format






import os

with ignored(OSError):
    os.remove('somefile.tmp')

other

iter

range
xrange
sorted()
sorted,x, reverse=True)
reversed()