Python · Синтаксис · Начальный уровень
Методы строк и f-strings
Изучите важнейшие встроенные методы строк и форматирование с помощью f-strings.
Краткое введение в тему и пояснения перед упражнениями (упражнения ниже):
f-strings
#Справочник: методы строк и f-strings
#Упражнения:
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
Очистить ввод
#Напишите функцию `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
Подсчёт слова
#Напишите функцию `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
Цензура слова
#Напишите функцию `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 *****
Соединить через дефис
#Напишите функцию `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
Проверить 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
Приветствие через 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.
Форматирование цены
#Напишите функцию `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
Безопасный поиск
#Напишите функцию `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
Текстовый прогресс-бар
#Напишите функцию `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%