""" Урок 23. Summary session 6 — весь код примеров одним файлом. Источник: subjects/python-fundamentals/course/lessons/23-summary-session-6/examples.html Файл собран автоматически (tools/build_lesson_examples.py): правьте страницу урока. Запуск: python lesson-23.py """ # ==================================================================== # Пример 1. Строки неизменяемы: методы возвращают новую строку # ==================================================================== text = " Python Summary " upper_text = text.upper() print(repr(text)) # ' Python Summary ' — исходная строка не изменилась print(repr(upper_text)) # ' PYTHON SUMMARY ' result = text.strip().lower().replace("python", "language") print(repr(result)) # 'language summary' # ==================================================================== # Пример 2. Предикаты: классификация текста # ==================================================================== def classify_token(token): if token.isdigit(): return "число" if token.isalpha(): return "слово" if token.isspace(): return "пробел" return "смешанный текст" tokens = ["2026", "Python", " ", "py3.14"] for token in tokens: print(repr(token), "->", classify_token(token)) # '2026' -> число # 'Python' -> слово # ' ' -> пробел # 'py3.14' -> смешанный текст print("Hello".startswith("He"), "Hello".endswith("lo")) # True True print("Hello World".istitle(), "hello world".istitle()) # True False # ==================================================================== # Пример 3. isdecimal(), isdigit(), isnumeric() — не одно и то же # ==================================================================== print("123".isdecimal(), "123".isdigit(), "123".isnumeric()) # True True True print("²".isdecimal(), "²".isdigit(), "²".isnumeric()) # False True True (надстрочная цифра ²) print("Ⅷ".isdecimal(), "Ⅷ".isdigit(), "Ⅷ".isnumeric()) # False False True (римская цифра Ⅷ) print("total_2026".isidentifier(), "2026_total".isidentifier()) # True False print("Python".isascii(), "Питон".isascii()) # True False print("line1\nline2".isprintable()) # False # ==================================================================== # Пример 4. Поиск подстроки: безопасный и «падающий» варианты # ==================================================================== text = "Python is awesome. Python is dynamic." print(text.find("Python"), text.rfind("Python")) # 0 19 print(text.find("Java")) # -1 print(text.count("Python")) # 2 try: text.index("Java") except ValueError as error: print("ValueError:", error) # ValueError: substring not found # ==================================================================== # Пример 5. Изменение регистра: шесть методов и одна ловушка # ==================================================================== text = "Hello, worlD! it's a TEST" print(text.upper()) # HELLO, WORLD! IT'S A TEST print(text.lower()) # hello, world! it's a test print(text.capitalize()) # Hello, world! it's a test print(text.title()) # Hello, World! It'S A Test print(text.swapcase()) # hELLO, WORLd! IT'S A test print("Straße".casefold(), "Straße".lower()) # strasse straße # ==================================================================== # Пример 6. Разделение и объединение: split(), rsplit(), splitlines(), join() # ==================================================================== data = "2026-08-13T10:30:00" print(data.split("-")) # ['2026', '08', '13T10:30:00'] print(data.split("-", 1)) # ['2026', '08-13T10:30:00'] print(data.rsplit("-", 1)) # ['2026-08', '13T10:30:00'] log = "line one\nline two\r\nline three" print(log.splitlines()) # ['line one', 'line two', 'line three'] fruits = "apple, banana, cherry" print([f.strip() for f in fruits.split(",")]) # ['apple', 'banana', 'cherry'] print(" | ".join(["a", "b", "c"])) # a | b | c # ==================================================================== # Пример 7. Очистка краёв: strip(), lstrip(), rstrip() # ==================================================================== raw = " ***Python 2026*** " print(f"[{raw.strip()}]") # [***Python 2026***] print(f"[{raw.strip().strip('*')}]") # [Python 2026] print(f"[{raw.lstrip()}]") # [***Python 2026*** ] print(f"[{raw.rstrip()}]") # [ ***Python 2026***] filename = "###important_notes###" print(filename.strip("#")) # important_notes # ==================================================================== # Пример 8. Выравнивание и заполнение: center(), ljust(), rjust(), zfill() # ==================================================================== rows = [("Alice", 92), ("Bob", 7), ("Carol", 105)] for row_name, score in rows: print(row_name.ljust(10, ".") + str(score).rjust(5)) # Alice..... 92 # Bob....... 7 # Carol..... 105 print("42".zfill(5)) # 00042 print("-42".zfill(5)) # -0042 print("hi".center(10, "*")) # ****hi**** # то же самое через спецификаторы f-строк label = "hi" print(f"{label:*^10}") # ****hi**** print(f"{label:*<10}") # hi******** print(f"{label:*>10}") # ********hi # ==================================================================== # Пример 9. removeprefix() и removesuffix() против ручной вырезки (Python 3.9+) # ==================================================================== filename = "test_report.txt" # современный способ name = filename.removeprefix("test_").removesuffix(".txt") print(name) # report # старый способ (Python < 3.9) old_name = filename if old_name.startswith("test_"): old_name = old_name[len("test_"):] if old_name.endswith(".txt"): old_name = old_name[:-len(".txt")] print(old_name) # report # безопасность: префикса нет — строка не меняется, ошибки не будет print("report.txt".removeprefix("test_")) # report.txt # ==================================================================== # Пример 10. Три способа форматирования рядом # ==================================================================== name, age, balance = "Alice", 30, 1234.5 print("Name: %s, Age: %d, Balance: %.2f" % (name, age, balance)) print("Name: {}, Age: {}, Balance: {:.2f}".format(name, age, balance)) print(f"Name: {name}, Age: {age}, Balance: {balance:.2f}") # Name: Alice, Age: 30, Balance: 1234.50 -- все три строки одинаковы # format() умеет переиспользовать и именовать аргументы print("{0} is {1} years old, {0} again".format(name, age)) # Alice is 30 years old, Alice again print("{n} is {a} years old".format(n=name, a=age)) # Alice is 30 years old # f-string вычисляет выражения и вызывает методы прямо внутри {} print(f"{name.upper()} turns {age + 1} next year") # ALICE turns 31 next year # ==================================================================== # Пример 11. Форматирование чисел: точность, разделители, знак, проценты # ==================================================================== prices = {"Book": 12.5, "Pen": 1.234, "Laptop": 1234.567} for item, price in prices.items(): print(f"{item:<10}{price:>10,.2f}") # Book 12.50 # Pen 1.23 # Laptop 1,234.57 pi = 3.14159265 print(f"{pi:.2f}") # 3.14 print(f"{pi:+.2f}") # +3.14 -- явный знак print(f"{1234567:,}") # 1,234,567 print(f"{42:05d}") # 00042 print(f"{0.256:.1%}") # 25.6% # ==================================================================== # Пример 12. Собираем приёмы вместе: проверка на панграмму # ==================================================================== import string def is_pangram(text): letters_used = {char for char in text.lower() if char.isalpha()} return letters_used >= set(string.ascii_lowercase) phrase = "The quick brown fox jumps over the lazy dog" print(is_pangram(phrase)) # True print(is_pangram("Hello world")) # False # вариант без множеств, через all() -- ближе к тому, что видно в уроке def is_pangram_v2(text): text_lower = text.lower() return all(letter in text_lower for letter in string.ascii_lowercase) print(is_pangram_v2(phrase)) # True