Python cheatsheet
Python cheatsheet
6k Follow Me
Python cheatsheet
The Python cheat sheet is a one-page reference sheet for the Python 3 programming language.
# Getting Started
Introduction Hello World Variables
See: Strings
list1 = ["apple", "banana", "cherry"] my_tuple = (1, 2, 3) set1 = {"a", "b", "c"}
list2 = [True, False, False] my_tuple = tuple((1, 2, 3)) set2 = set(("a", "b", "c"))
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))
Dictionary - Casting
Integers
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
x = int(1) # x will be 1
>>> a["one"]
y = int(2.8) # y will be 2
1
z = int("3") # z will be 3
>>> a.keys()
dict_keys(['one', 'two', 'three'])
Floats
>>> a.values()
dict_values([1, 2, 3]) x = float(1) # x will be 1.0
>>> a.update({"four": 4}) y = float(2.8) # y will be 2.8
>>> a.keys() z = float("3") # z will be 3.0
dict_keys(['one', 'two', 'three', 'four']) w = float("4.2") # w will be 4.2
>>> a['four']
4 Strings
# Python Strings
Array-like Looping Slicing string
Get the character at position 1 or last Loop through the letters in the word "foo" >>> s = 'mybacon'
>>> s[2:5]
'bac'
String Length Multiple copies >>> s[0:2]
'my'
>>> hello = "Hello, World!" >>> s = '===+'
>>> print(len(hello)) >>> n = 8
13 >>> s * n >>> s = 'mybacon'
'===+===+===+===+===+===+===+===+' >>> s[:2]
'my'
The len() function returns the length of a string
>>> s[2:]
'bacon'
Check String Concatenates
>>> s[:2] + s[2:]
'mybacon'
>>> s = 'spam' >>> s = 'spam' >>> s[:]
>>> s in 'I saw spamalot!' >>> t = 'egg' 'mybacon'
True >>> s + t
>>> s not in 'I saw The Holy Grail!' 'spamegg'
>>> s = 'mybacon'
True >>> 'spam' 'egg'
>>> s[-5:-1]
'spamegg'
'baco'
>>> s[2:6]
'baco'
Formatting
With a stride
name = "John"
print("Hello, %s!" % name)
>>> s = '12345' * 5
>>> s
name = "John" '1234512345123451234512345'
age = 23 >>> s[::5]
print("%s is %d years old." % (name, age)) '11111'
>>> s[4::5]
format() Method '55555'
>>> s[::-5]
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36) '55555'
txt2 = "My name is {0}, I'm {1}".format("John", 36) >>> s[::-1]
txt3 = "My name is {}, I'm {}".format("John", 36) '5432154321543215432154321'
>>> name = input("Enter your name: ") >>> "#".join(["John", "Peter", "Vicky"]) >>> "Hello, world!".endswith("!")
Enter your name: Tom 'John#Peter#Vicky' True
>>> name
'Tom'
>>> website = 'Quickref.ME' >>> f'{"text":10}' # [width] >>> f'{10:b}' # binary type
>>> f"Hello, {website}" 'text ' '1010'
"Hello, Quickref.ME" >>> f'{"test":*>10}' # fill left >>> f'{10:o}' # octal type
'******test' '12'
>>> num = 10 >>> f'{"test":*<10}' # fill right >>> f'{200:x}' # hexadecimal type
>>> f'{num} + 10 = {num + 10}' 'test******' 'c8'
'10 + 10 = 20' >>> f'{"test":*^10}' # fill center >>> f'{200:X}'
'***test***' 'C8'
>>> f"""He said {"I'm John"}""" >>> f'{12345:0>10}' # fill with numbers >>> f'{345600000000:e}' # scientific notation
"He said I'm John" '0000012345' '3.456000e+11'
>>> f'{65:c}' # character type
>>> f'5 {"{stars}"}' 'A'
'5 {stars}' >>> f'{10:#b}' # [type] with notation (bas
>>> f'{{5}} {"stars"}' '0b1010'
'{5} stars' >>> f'{10:#o}'
'0o12'
>>> name = 'Eric' >>> f'{10:#x}'
>>> age = 27 '0xa'
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
# Python Lists
Defining Generate
Omitting index
With a stride
Access
# Python Loops
Basic With index While
words = ['Mon', 'Tue', 'Wed'] nums = [60, 70, 30, 110, 90]
nums = [1, 2, 3] for n in nums:
# Use zip to pack into a tuple list if n > 100:
for w, n in zip(words, nums): print("%d is bigger than 100" %n)
print('%d:%s, ' %(n, w)) break
else:
print("Not found!")
# Python Functions
Basic Return Positional arguments
Anonymous functions
# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)
# Python Modules
Import modules From a module Import all
import math from math import ceil, floor from math import *
print(math.sqrt(16)) # => 4.0 print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
with open("myfile.txt") as file: contents = {"aa": 12, "bb": 21} contents = {"aa": 12, "bb": 21}
for line in file: with open("myfile1.txt", "w+") as file: with open("myfile2.txt", "w+") as file:
print(line) file.write(str(contents)) file.write(json.dumps(contents))
file = open('myfile.txt', 'r') with open('myfile1.txt', "r+") as file: with open('myfile2.txt', "r+") as file:
for i, line in enumerate(file, start=1): contents = file.read() contents = json.load(file)
print("Number %s: %s" % (i, line)) print(contents) print(contents)
# Miscellaneous
Comments Generators Generator to list
# This is a single line comments. def double_numbers(iterable): values = (-x for x in [1,2,3,4,5])
for i in iterable: gen_to_list = list(values)
yield i + i
""" Multiline strings can be written
# => [-1, -2, -3, -4, -5]
using three "s, and are often used
print(gen_to_list)
as documentation.
"""
Handle exceptions
try:
# Use "raise" to raise an error
raise IndexError("This is an index error")
except IndexError as e:
pass # Pass is just a no-op. Usually you would do recovery here.
except (TypeError, NameError):
pass # Multiple exceptions can be handled together, if required.
else: # Optional clause to the try/except block. Must follow all except blocks
print("All good!") # Runs only if the code in try raises no exceptions
finally: # Execute under all circumstances
print("We can clean up resources here")
中文版 #Notes
PyTorch Cheatsheet Taskset Cheatsheet
Quick Reference Quick Reference