Python 기술


숫자를 쉽게 포매팅한 문자로 변환

print(f"{len(words):,}")

Enumerate 사용 예

for i, item in enumerate(items):
    process(i, item)

문자를 숫자로 전환

print(ord('A'))  # 출력: 65
print(ord('가'))  # 출력: 44032

바다코끼리 연산자(Walrus Operator)

before

val = get_data()
while not predicate(val):
    print("Current value acceptable:", val)

after

while not predicate(val := get_data()):
    print("Current value acceptable:", val)

another examples

if (match := pattern.search(data)) is not None:
    print("Found:", match.group(0))

results = [y := f(x), y**2, y**3 for x in range(5)]

namedtuple 사용하기

# 점수를 저장하는 namedtuple 정의
Score = namedtuple('Score', ['name', 'points'])

# 여러 점수 저장
scores = [
    Score('Alice', 95),
    Score('Bob', 87),
    Score('Charlie', 92)
]

# 이름을 통해 데이터 접근
for score in scores:
    print(f'{score.name} scored {score.points} points.')

Path().read_text()로 파일 읽기

읽기

from pathlib import Path

content = Path("station-names.txt").read_text()

Context Manager

class MyContextManager:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting the context")
        if exc_type:
            print(f"An exception occurred: {exc_val}")
        return True  # 예외를 처리했음을 알림 (False일 경우 예외가 재발생)

with MyContextManager() as manager:
    print("Inside the context")
    # raise ValueError("Something went wrong")  # 예외가 발생하더라도 __exit__가 실행됨
with (
    open("station-names.txt") as names,
    open("station-latitudes.txt") as lats,
    open("station-longitudes.txt") as lons,
    open("station-elevations.txt") as els
):
    for data in zip(names, lats, lons, els):
        data = (field.rstrip() for field in data)

print

import pprint

data = [
    {'name': 'Alice', 'age': 30, 'hobbies': ['reading', 'gardening']},
    {'name': 'Bob', 'age': 25, 'hobbies': ['gaming', 'coding']},
    {'name': 'Charlie', 'age': 35, 'hobbies': ['hiking', 'swimming']}
]

pprint.pprint(data)

Output


[{'age': 30, 'hobbies': ['reading', 'gardening'], 'name': 'Alice'},
 {'age': 25, 'hobbies': ['gaming', 'coding'], 'name': 'Bob'},
 {'age': 35, 'hobbies': ['hiking', 'swimming'], 'name': 'Charlie'}]

open으로 연 파일은 이터러블

with open('example.txt') as fd:
    for line in fd:
        line = line.rstrip()  # 개행 문자 제거
        print(repr(line))

@ 윈도우의 개행은 \r\n 이지만 open으로 파일을 읽으면 \n으로 자동 변환됨. 이게 싫으면 open으로 열때 rb로 열것

repr


x = 10
print(repr(x))  # 출력: '10'

text = "Hello, world!"
print(repr(text))  # 출력: "'Hello, world!'"

my_list = [1, 2, 3]
print(repr(my_list))  # 출력: '[1, 2, 3]'

zip, zip_longest


a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']

zipped = zip(a, b)
print(list(zipped))  # 출력: [(1, 'a'), (2, 'b'), (3, 'c')]



a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']

try:
    zipped_strict = zip(a, b, strict=True)
    print(list(zipped_strict))
except ValueError as e:
    print(e)  # 출력: zip() argument 2 is longer than argument 1



a = [1, 2, 3]
b = ['a', 'b', 'c', 'd']

try:
    zipped_strict = zip(a, b, strict=True)
    print(list(zipped_strict))
except ValueError as e:
    print(e)  # 출력: zip() argument 2 is longer than argument 1