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%