Python 치트 시트
검색 및 인쇄 가능한 Python 3 레퍼런스 — 구문, 데이터 구조, 컴프리헨션, 함수, 클래스, 파일, 표준 라이브러리. 무료.
Variables & types
10x = 1
Assign a variable (dynamically typed)
x: int = 1
Optional type annotation
a, b = 1, 2
Multiple assignment
type(x)
Get the type of a value
int('42')
Convert a string to an integer
str(42)
Convert a value to a string
isinstance(x, int)
Type check
None
The null/absence value
x = y = 0
Chained assignment
PI: Final = 3.14
Constant hint (typing.Final)
Strings
11f'Hello {name}'
f-string interpolation
len(s)
String length
s.upper()
Convert to upper case
s.strip()
Remove surrounding whitespace
s.split(',')
Split into a list
','.join(items)
Join a list with a separator
s.replace('a', 'b')
Replace substrings
'a' in s
Membership test
s[1:4]
Slice characters 1 to 3
s[::-1]
Reverse a string
s.startswith('a')
Check the prefix
Lists & tuples
10a = [1, 2, 3]
Create a list
a.append(4)
Add an item to the end
a.insert(0, x)
Insert at an index
a.pop()
Remove and return the last item
a[1:3]
Slice a sublist
sorted(a, reverse=True)
Return a sorted copy
a.sort(key=len)
Sort in place by a key
len(a)
Number of items
t = (1, 2)
Immutable tuple
first, *rest = a
Unpack with a star
Dicts & sets
10d = {'k': 'v'}
Create a dictionary
d['k']
Access a value by key
d.get('k', default)
Get with a fallback
d.keys() / d.values()
View keys or values
d.items()
Iterate key/value pairs
{**a, **b}
Merge dictionaries
a | b
Dict/set union operator
del d['k']
Remove a key
s = {1, 2, 3}
Create a set (unique values)
set(a) & set(b)
Set intersection
Comprehensions
8[x * 2 for x in a]
List comprehension
[x for x in a if x > 0]
Filtered comprehension
{x: x**2 for x in a}
Dict comprehension
{x for x in a}
Set comprehension
(x for x in a)
Generator expression (lazy)
[y for row in m for y in row]
Flatten with nested loops
[a if c else b for x in items]
Conditional value in comprehension
sum(x for x in a)
Aggregate a generator
Control flow
9if x > 0:\n ...
Conditional (indentation matters)
elif / else:
Additional branches
a if cond else b
Ternary expression
for x in range(10):
Loop over a range
for i, x in enumerate(a):
Loop with an index
for a, b in zip(x, y):
Loop two iterables together
while cond:
Loop while true
break / continue
Exit or skip an iteration
match x:\n case 1: ...
Structural pattern matching (3.10+)
Functions
8def f(a, b=1): return a + b
Function with a default argument
def f(*args, **kwargs):
Variadic positional + keyword args
f(name='Sam')
Call with a keyword argument
lambda x: x + 1
Anonymous inline function
def f(a: int) -> int:
Type hints for params and return
@decorator
Wrap a function with a decorator
yield value
Produce a value from a generator
global x / nonlocal x
Rebind an outer-scope variable
Classes
9class A(Base):
Class with inheritance
def __init__(self, x):
Constructor / initializer
self.x = x
Instance attribute
def __str__(self):
String representation
@property
Computed read-only attribute
@staticmethod / @classmethod
Static and class methods
super().__init__()
Call the parent initializer
@dataclass
Auto-generate init/repr/eq
isinstance(obj, A)
Check the instance type
Files, errors & modules
9with open('f.txt') as fh:
Open a file (auto-closed)
fh.read() / fh.readlines()
Read file contents
open('f.txt', 'w').write(s)
Write to a file
try:\n ...\nexcept ValueError as e:
Catch a specific exception
raise ValueError('bad')
Raise an exception
finally:
Always-run cleanup block
import os
Import a module
from math import sqrt
Import a specific name
import numpy as np
Import with an alias
“:q”와 일치하는 항목이 없습니다.
Python 치트 시트 소개
이 Python 치트 시트는 변수와 타입, 문자열, 리스트와 튜플, 딕셔너리와 세트, 컴프리헨션, 제어 흐름, 함수, 클래스, 파일/오류/모듈까지 Python 3를 검색 가능한 한 페이지로 압축했습니다. 각 항목은 작동하는 코드와 짧은 설명을 함께 보여줍니다.
f-문자열, 슬라이싱, 리스트와 딕셔너리 컴프리헨션, 언패킹, 기본값과 키워드 인수, 컨텍스트 매니저, 예외 처리 같은 관용적인 Python에 기반을 두고 있어, Python이 매일 쓰는 언어든 가끔 돌아오는 언어든 빠르게 감을 되찾는 용도로 유용합니다.
이 시트는 무료이며 완전히 클라이언트 사이드로 동작합니다. 검색창으로 실시간 필터링하고, 고정된 섹션 메뉴로 이동하며, 클릭 한 번으로 스니펫을 복사하고, 키보드 옆에 두고 싶을 때는 전체 참조 자료를 인쇄하세요.
Python 치트 시트 사용 방법
- 섹션을 훑어보세요 — 변수 & 타입부터 컴프리헨션을 지나 파일, 오류 & 모듈까지.
- 검색창에 입력해 시트 전체의 모든 스니펫을 실시간으로 필터링하세요.
- 고정된 목차를 사용해 딕셔너리 & 세트 같은 섹션으로 바로 이동하세요.
- 스니펫이나 복사 아이콘을 클릭해 Python 코드를 복사하세요.
- 오프라인용 Python 3 참조 자료로 페이지를 인쇄하세요.
자주 묻는 질문
Python 3입니다. f-문자열, 컴프리헨션, 언패킹, 컨텍스트 매니저 같은 현재 관용구를 사용하므로 최신 Python 3 인터프리터 어디에서나 실행됩니다.
아홉 개 섹션입니다: 변수와 타입, 문자열, 리스트와 튜플, 딕셔너리와 세트, 컴프리헨션, 제어 흐름, 함수, 클래스, 파일/오류/모듈 — 일상적인 스크립트에서 사용하는 표준 라이브러리의 핵심 부분입니다.
공식 문서는 방대하지만, 이 시트는 의도적으로 간결하게 만들어졌습니다. 각 패턴의 한 줄짜리 형태와 짧은 설명을 보여주어 몇 초 안에 찾아보고 복사한 뒤 넘어갈 수 있습니다.
네 — 스니펫이나 마우스를 올렸을 때 나타나는 복사 아이콘을 클릭하면 "복사됨!" 확인과 함께 곧바로 클립보드에 복사됩니다.
네, 완전 무료입니다. 브라우저에서 로드되며 계정이 필요 없고 인쇄도 가능합니다.
인기 검색어
python cheat sheet
python syntax reference
python list methods
python dictionary methods
python string methods
list comprehension python
python classes example
python file handling
도움이 필요하신가요?
이 도구에서 문제를 발견하셨나요? 저희 팀에 알려주세요.