Telegram Group & Telegram Channel
🐍 7 “бесполезных” функций Python, которые на самом деле полезны

Инструменты из стандартной библиотеки, которые могут удивить:

1. textwrap.dedent() — убирает отступы у многострочного текста.

import textwrap
text = textwrap.dedent(\"\"\"
Привет!
Это текст с отступами.
\"\"\").strip()
print(text)

2. difflib.get_close_matches() — находит схожие строки.

import difflib
words = ["python", "java", "javascript"]
print(difflib.get_close_matches("javascrip", words))

3. uuid.uuid4() — создает уникальный идентификатор.

import uuid
print(uuid.uuid4())

4. shutil.get_terminal_size() — определяет размеры терминала.

import shutil
columns, rows = shutil.get_terminal_size()
print(f"Размер терминала: {columns}x{rows}")

5. functools.lru_cache() — сохраняет результаты функции в кэше.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(100))

6. itertools.groupby() — группирует элементы по ключу.

from itertools import groupby
data = [(&apos;fruit&apos;, &apos;apple&apos;), (&apos;fruit&apos;, &apos;banana&apos;), (&apos;veg&apos;, &apos;carrot&apos;)]
for key, group in groupby(data, lambda x: x[0]):
print(key, list(group))

7. contextlib.suppress() — элегантная альтернатива конструкции try-except.

from contextlib import suppress
with suppress(FileNotFoundError):
open("not_exist.txt")

@Python_Community_ru



tg-me.com/Python_Community_ru/2569
Create:
Last Update:

🐍 7 “бесполезных” функций Python, которые на самом деле полезны

Инструменты из стандартной библиотеки, которые могут удивить:

1. textwrap.dedent() — убирает отступы у многострочного текста.

import textwrap
text = textwrap.dedent(\"\"\"
Привет!
Это текст с отступами.
\"\"\").strip()
print(text)

2. difflib.get_close_matches() — находит схожие строки.

import difflib
words = ["python", "java", "javascript"]
print(difflib.get_close_matches("javascrip", words))

3. uuid.uuid4() — создает уникальный идентификатор.

import uuid
print(uuid.uuid4())

4. shutil.get_terminal_size() — определяет размеры терминала.

import shutil
columns, rows = shutil.get_terminal_size()
print(f"Размер терминала: {columns}x{rows}")

5. functools.lru_cache() — сохраняет результаты функции в кэше.

from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n-1) + fib(n-2)
print(fib(100))

6. itertools.groupby() — группирует элементы по ключу.

from itertools import groupby
data = [(&apos;fruit&apos;, &apos;apple&apos;), (&apos;fruit&apos;, &apos;banana&apos;), (&apos;veg&apos;, &apos;carrot&apos;)]
for key, group in groupby(data, lambda x: x[0]):
print(key, list(group))

7. contextlib.suppress() — элегантная альтернатива конструкции try-except.

from contextlib import suppress
with suppress(FileNotFoundError):
open("not_exist.txt")

@Python_Community_ru

BY Python Community


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/Python_Community_ru/2569

View MORE
Open in Telegram


Python Community Telegram | DID YOU KNOW?

Date: |

Traders also expressed uncertainty about the situation with China Evergrande, as the indebted property company has not provided clarification about a key interest payment.In economic news, the Commerce Department reported an unexpected increase in U.S. new home sales in August.Crude oil prices climbed Friday and front-month WTI oil futures contracts saw gains for a fifth straight week amid tighter supplies. West Texas Intermediate Crude oil futures for November rose $0.68 or 0.9 percent at 73.98 a barrel. WTI Crude futures gained 2.8 percent for the week.

A project of our size needs at least a few hundred million dollars per year to keep going,” Mr. Durov wrote in his public channel on Telegram late last year. “While doing that, we will remain independent and stay true to our values, redefining how a tech company should operate.

Python Community from jp


Telegram Python Community
FROM USA