Python · Синтаксис · Начальный уровень

Методы строк и f-strings

10 задач

Изучите важнейшие встроенные методы строк и форматирование с помощью f-strings.

Методы строк

#
Строки в Python — это неизменяемые (immutable) последовательности символов. Каждый метод строки возвращает **новую** строку, оригинал не изменяется. ## Изменение регистра ```python text = "hello world" print(text.upper()) # "HELLO WORLD" print(text.lower()) # "hello world" print(text.capitalize()) # "Hello world" print(text.title()) # "Hello World" print(text.swapcase()) # "HELLO WORLD" ``` ## Удаление пробелов ```python s = " hello " print(s.strip()) # "hello" — с обеих сторон print(s.lstrip()) # "hello " — только слева print(s.rstrip()) # " hello" — только справа ``` `strip()` — самый распространённый способ очистить пользовательский ввод. ## Поиск и проверка ```python s = "Python is great" print(s.find("is")) # 7 — индекс первого вхождения, -1 если не найдено print(s.index("is")) # 7 — то же, но кидает ValueError если не найдено print(s.count("t")) # 2 print(s.startswith("Py")) # True print(s.endswith("eat")) # True print("123".isdigit()) # True print("abc".isalpha()) # True print("abc123".isalnum()) # True ``` ## Замена и разбиение ```python s = "one two three" print(s.replace("two", "2")) # "one 2 three" print(s.split()) # ["one", "two", "three"] print(s.split(" ", maxsplit=1)) # ["one", "two three"] ``` `split()` без аргументов разбивает по любым пробелам и удаляет пустые элементы. ## Объединение ```python words = ["one", "two", "three"] print(", ".join(words)) # "one, two, three" print("-".join(words)) # "one-two-three" print("".join(words)) # "onetwothree" ``` `join` — это обратное к `split`: всегда вызывается на **разделителе**, а не на списке. ## Выравнивание и заполнение ```python s = "hello" print(s.ljust(10)) # "hello " print(s.rjust(10)) # " hello" print(s.center(11, "-")) # "---hello---" print("42".zfill(5)) # "00042" ``` ## Главное правило Поскольку строки неизменяемы, нужно **присваивать** результат: ```python name = " Alice " name = name.strip() # правильно name.strip() # ничего не происходит — результат отбрасывается ```

f-strings

#
f-strings (форматированные строковые литералы) — это современный и читабельный способ встраивать значения и выражения прямо в строки. Они быстрее `%`-форматирования и `.format()`. ## Базовый синтаксис ```python name = "Alice" age = 30 print(f"Hello, {name}! You are {age} years old.") # Hello, Alice! You are 30 years old. ``` Внутри `{}` можно помещать любую переменную или выражение: ```python a, b = 7, 3 print(f"{a} + {b} = {a + b}") # 7 + 3 = 10 print(f"{'hello'.upper()}") # HELLO ``` ## Форматирование чисел ```python price = 9.5 pi = 3.14159 score = 0.876 print(f"{price:.2f}") # 9.50 — 2 знака после запятой print(f"{pi:.4f}") # 3.1416 — 4 знака после запятой print(f"{score:.1%}") # 87.6% — процент print(f"{1000000:,}") # 1,000,000 — разделитель тысяч print(f"{42:08d}") # 00000042 — целое с нулями print(f"{42:>10}") # 42 — выравнивание вправо print(f"{42:<10}") # 42 — выравнивание влево print(f"{42:^10}") # 42 — по центру ``` ## Отладка с `=` ```python x = 42 items = [1, 2, 3] print(f"{x=}") # x=42 print(f"{items=}") # items=[1, 2, 3] print(f"{len(items)=}") # len(items)=3 ``` Спецификатор `=` выводит и само выражение, и его значение — идеально для быстрой отладки. ## Многострочные f-strings ```python name = "Bob" total = 123.45 message = ( f"Итог заказа\n" f"Клиент: {name}\n" f"Сумма: ${total:.2f}" ) print(message) # Итог заказа # Клиент: Bob # Сумма: $123.45 ``` ## Практический пример ```python def format_report(name, score, passed): status = "PASS" if passed else "FAIL" return f"[{status}] {name}: {score:.1f}/100" print(format_report("Alice", 87.5, True)) # [PASS] Alice: 87.5/100 print(format_report("Bob", 45.0, False)) # [FAIL] Bob: 45.0/100 ```

Справочник: методы строк и f-strings

#
## Методы строк | Метод | Что делает | Пример | |---|---|---| | `s.upper()` | ВСЕ ЗАГЛАВНЫЕ | `"hi".upper()` → `"HI"` | | `s.lower()` | все строчные | `"HI".lower()` → `"hi"` | | `s.capitalize()` | Первая заглавная | `"hi".capitalize()` → `"Hi"` | | `s.title()` | Каждое Слово С Заглавной | `"hi there".title()` → `"Hi There"` | | `s.strip()` | Удалить пробелы с обеих сторон | `" hi ".strip()` → `"hi"` | | `s.lstrip()` / `s.rstrip()` | Только слева / справа | — | | `s.replace(old, new)` | Заменить все вхождения | `"aXa".replace("X","b")` → `"aba"` | | `s.split(sep)` | Разбить на список | `"a,b".split(",")` → `["a","b"]` | | `sep.join(lst)` | Объединить список в строку | `",".join(["a","b"])` → `"a,b"` | | `s.find(sub)` | Индекс первого вхождения (-1 если нет) | `"abc".find("b")` → `1` | | `s.index(sub)` | Индекс (кидает ValueError) | — | | `s.count(sub)` | Подсчёт вхождений | `"aaa".count("a")` → `3` | | `s.startswith(p)` | Начинается с префикса | `"abc".startswith("ab")` → `True` | | `s.endswith(p)` | Заканчивается суффиксом | `"abc".endswith("bc")` → `True` | | `s.isdigit()` | Все цифры | `"123".isdigit()` → `True` | | `s.isalpha()` | Все буквы | `"abc".isalpha()` → `True` | | `s.isalnum()` | Буквы и цифры | — | | `s.ljust(n)` | Выровнять влево в ширине n | — | | `s.rjust(n)` | Выровнять вправо | — | | `s.center(n, c)` | По центру, заполнить c | — | | `s.zfill(n)` | Заполнить нулями до ширины n | `"7".zfill(3)` → `"007"` | ## Спецификаторы формата f-string | Спецификатор | Значение | Пример | |---|---|---| | `:.2f` | Вещественное, 2 знака | `f"{3.1:.2f}"` → `"3.10"` | | `:.1%` | Процент, 1 знак | `f"{0.875:.1%}"` → `"87.5%"` | | `:,` | Разделитель тысяч | `f"{1000:,}"` → `"1,000"` | | `:05d` | Целое с нулями | `f"{7:05d}"` → `"00007"` | | `:>10` | Выравнивание вправо | `f"{'x':>10}"` → `" x"` | | `:<10` | Выравнивание влево | `f"{'x':<10}"` → `"x "` | | `:^10` | По центру | `f"{'x':^10}"` → `" x "` | | `=` | Отладка: имя=значение | `f"{x=}"` → `"x=42"` | ## Распространённые паттерны ```python # Очистить ввод пользователя clean = user_input.strip().lower() # Проверить и трансформировать if s.startswith("http"): s = s[len("http"):] # Собрать предложение из списка слов sentence = " ".join(words) + "." # Форматирование строки таблицы row = f"{name:<20} {score:>6.1f} {'PASS' if score >= 60 else 'FAIL'}" ```
01

Title Case для имени

#

Напишите функцию `format_name(name)`, которая принимает строку и возвращает её в формате title case (каждое слово с заглавной буквы). Пример: `format_name("john doe")` → `"John Doe"`.

def format_name(name):
    pass


print(format_name("john doe"))      # John Doe
print(format_name("ALICE SMITH"))   # Alice Smith
Решение
def format_name(name):
    return name.title()


print(format_name("john doe"))      # John Doe
print(format_name("ALICE SMITH"))   # Alice Smith
02

Очистить ввод

#

Напишите функцию `clean(s)`, которая удаляет пробелы в начале/конце строки и переводит её в нижний регистр. Пример: `clean(" Hello World ")` → `"hello world"`.

def clean(s):
    pass


print(clean("  Hello World  "))   # hello world
print(clean("  Python  "))        # python
Решение
def clean(s):
    return s.strip().lower()


print(clean("  Hello World  "))   # hello world
print(clean("  Python  "))        # python
03

Подсчёт слова

#

Напишите функцию `count_word(text, word)`, которая подсчитывает, сколько раз `word` встречается в `text` (без учёта регистра). Пример: `count_word("Apple apple APPLE", "apple")` → `3`.

def count_word(text, word):
    pass


print(count_word("Apple apple APPLE", "apple"))  # 3
print(count_word("cat cat dog cat", "cat"))      # 3
Решение
def count_word(text, word):
    return text.lower().count(word.lower())


print(count_word("Apple apple APPLE", "apple"))  # 3
print(count_word("cat cat dog cat", "cat"))      # 3
04

Цензура слова

#

Напишите функцию `censor(text, word)`, которая заменяет все вхождения `word` в `text` звёздочками той же длины. Пример: `censor("I love cats", "cats")` → `"I love ****"`.

def censor(text, word):
    pass


print(censor("I love cats", "cats"))    # I love ****
print(censor("hello world", "world"))   # hello *****
Решение
def censor(text, word):
    return text.replace(word, "*" * len(word))


print(censor("I love cats", "cats"))    # I love ****
print(censor("hello world", "world"))   # hello *****
05

Соединить через дефис

#

Напишите функцию `dashify(s)`, которая разбивает строку на слова и соединяет их через дефис. Пример: `dashify("hello world foo")` → `"hello-world-foo"`.

def dashify(s):
    pass


print(dashify("hello world foo"))   # hello-world-foo
print(dashify("one two three"))     # one-two-three
Решение
def dashify(s):
    return "-".join(s.split())


print(dashify("hello world foo"))   # hello-world-foo
print(dashify("one two three"))     # one-two-three
06

Проверить URL

#

Напишите функцию `is_url(s)`, которая возвращает `True`, если строка начинается с `"http://"` или `"https://"` и заканчивается на `".com"`, `".org"` или `".net"`. Иначе возвращает `False`.

def is_url(s):
    pass


print(is_url("https://example.com"))   # True
print(is_url("http://site.org"))       # True
print(is_url("ftp://bad.com"))         # False
print(is_url("https://no-ext.xyz"))    # False
Решение
def is_url(s):
    starts_ok = s.startswith("http://") or s.startswith("https://")
    ends_ok = s.endswith(".com") or s.endswith(".org") or s.endswith(".net")
    return starts_ok and ends_ok


# Короткий вариант с кортежами:
def is_url_v2(s):
    return s.startswith(("http://", "https://")) and s.endswith((".com", ".org", ".net"))


print(is_url("https://example.com"))   # True
print(is_url("ftp://bad.com"))         # False
07

Приветствие через f-string

#

Напишите функцию `greet(name, age)`, которая возвращает приветствие через f-string: `"Hello, {name}! You are {age} years old."`. Пример: `greet("Alice", 25)` → `"Hello, Alice! You are 25 years old."`.

def greet(name, age):
    pass


print(greet("Alice", 25))   # Hello, Alice! You are 25 years old.
print(greet("Bob", 30))     # Hello, Bob! You are 30 years old.
Решение
def greet(name, age):
    return f"Hello, {name}! You are {age} years old."


print(greet("Alice", 25))   # Hello, Alice! You are 25 years old.
print(greet("Bob", 30))     # Hello, Bob! You are 30 years old.
08

Форматирование цены

#

Напишите функцию `format_price(amount)`, которая форматирует число как цену с 2 знаками после запятой и префиксом `$`. Пример: `format_price(9.5)` → `"$9.50"`, `format_price(1000)` → `"$1,000.00"`.

def format_price(amount):
    pass


print(format_price(9.5))     # $9.50
print(format_price(1000))    # $1,000.00
print(format_price(0.99))    # $0.99
Решение
def format_price(amount):
    return f"${amount:,.2f}"


print(format_price(9.5))     # $9.50
print(format_price(1000))    # $1,000.00
print(format_price(0.99))    # $0.99
09

Безопасный поиск

#

Напишите функцию `safe_find(text, sub)`, которая возвращает индекс первого вхождения `sub` в `text`, или `-1` если не найдено. НЕ используйте `.index()`. Пример: `safe_find("hello", "ll")` → `2`, `safe_find("hello", "x")` → `-1`.

def safe_find(text, sub):
    pass


print(safe_find("hello", "ll"))   # 2
print(safe_find("hello", "x"))    # -1
print(safe_find("python", "on"))  # 4
Решение
def safe_find(text, sub):
    return text.find(sub)


print(safe_find("hello", "ll"))   # 2
print(safe_find("hello", "x"))    # -1
print(safe_find("python", "on"))  # 4
10

Текстовый прогресс-бар

#

Напишите функцию `progress_bar(done, total, width=20)`, которая возвращает текстовый прогресс-бар. Заполнение `"#"` для выполненной части, `"."` для остатка. Пример: `progress_bar(3, 10, 10)` → `"[###.......] 30%"`.

def progress_bar(done, total, width=20):
    pass


print(progress_bar(3, 10, 10))    # [###.......] 30%
print(progress_bar(0, 10, 10))    # [..........] 0%
print(progress_bar(10, 10, 10))   # [##########] 100%
Решение
def progress_bar(done, total, width=20):
    filled = int(width * done / total)
    bar = "#" * filled + "." * (width - filled)
    percent = done / total
    return f"[{bar}]{percent:>5.0%}"


print(progress_bar(3, 10, 10))    # [###.......] 30%
print(progress_bar(0, 10, 10))    # [..........] 0%
print(progress_bar(10, 10, 10))   # [##########] 100%