Работа с вводом и выводом -- фундаментальный навык. Python предоставляет мощные инструменты для форматирования текста, от простых f-строк до новых template strings в Python 3.14.
Функция input()
input() считывает строку с клавиатуры:
# Basic input
name = input("Как вас зовут? ")
print(f"Привет, {name}!")
# input() ALWAYS returns a string
age_str = input("Ваш возраст: ")
print(type(age_str)) # <class 'str'>
# Convert to the needed type
age = int(age_str)
year_of_birth = 2026 - age
# One-liner conversion
height = float(input("Ваш рост (м): "))
# Read multiple values on one line
x, y = input("Координаты (x y): ").split()
x, y = int(x), int(y)
# Read a list of numbers
numbers = list(map(int, input("Числа через пробел: ").split()))
print(sum(numbers))
Безопасный ввод с обработкой ошибок
def get_integer(prompt: str) -> int:
"""Safely read an integer from user input."""
while True:
try:
return int(input(prompt))
except ValueError:
print("Ошибка! Введите целое число.")
age = get_integer("Ваш возраст: ")
f-строки (f-strings)
F-строки -- самый удобный и быстрый способ форматирования в Python:
name = "Иван"
age = 25
# Basic f-string
print(f"Имя: {name}, возраст: {age}")
# Expressions inside braces
print(f"Через 10 лет будет {age + 10}")
print(f"Имя в верхнем регистре: {name.upper()}")
# Calling functions
items = [3, 1, 4, 1, 5]
print(f"Сортировка: {sorted(items)}")
# Multiline f-strings
info = (
f"Пользователь: {name}\n"
f"Возраст: {age}\n"
f"Статус: {'совершеннолетний' if age >= 18 else 'несовершеннолетний'}"
)
print(info)
# Nested quotes
print(f"{'Привет':>20}") # right-aligned
print(f"Результат: {{'ключ': 'значение'}}") # literal braces with {{}}
Отладочный формат (=)
Python 3.8+ поддерживает оператор = в f-строках для отладки:
x = 42
y = 3.14
name = "Python"
# Debug format - shows expression and its value
print(f"{x = }") # x = 42
print(f"{y = :.1f}") # y = 3.1
print(f"{name = !r}") # name = 'Python'
print(f"{x + y = }") # x + y = 45.14
print(f"{len(name) = }") # len(name) = 6
# Great for debugging
data = [1, 2, 3]
print(f"{data = }, {len(data) = }, {sum(data) = }")
# data = [1, 2, 3], len(data) = 3, sum(data) = 6
Спецификаторы формата
F-строки поддерживают мини-язык форматирования после двоеточия:
# Number formatting
n = 1234567.89
print(f"{n:,.2f}") # 1,234,567.89 (thousands separator + 2 decimals)
print(f"{n:_.2f}") # 1_234_567.89 (underscore separator)
print(f"{n:.0f}") # 1234568 (no decimals, rounded)
print(f"{n:e}") # 1.234568e+06 (scientific notation)
print(f"{n:.2e}") # 1.23e+06
# Integer formatting
x = 42
print(f"{x:05d}") # 00042 (zero-padded, width 5)
print(f"{x:b}") # 101010 (binary)
print(f"{x:o}") # 52 (octal)
print(f"{x:x}") # 2a (hex lowercase)
print(f"{x:X}") # 2A (hex uppercase)
print(f"{x:#x}") # 0x2a (hex with prefix)
print(f"{x:#010x}") # 0x0000002a
# Percentage
ratio = 0.856
print(f"{ratio:.1%}") # 85.6%
print(f"{ratio:%}") # 85.600000%
# String alignment
text = "Python"
print(f"{text:<20}") # 'Python ' (left-aligned)
print(f"{text:>20}") # ' Python' (right-aligned)
print(f"{text:^20}") # ' Python ' (centered)
print(f"{text:*^20}") # '*******Python*******' (fill with *)
print(f"{text:.3}") # 'Pyt' (truncate to 3 chars)
Форматирование дат
from datetime import datetime
now = datetime.now()
print(f"{now:%Y-%m-%d}") # 2026-03-30
print(f"{now:%d.%m.%Y %H:%M}") # 30.03.2026 14:30
print(f"{now:%A, %B %d}") # Monday, March 30
# Custom date format
print(f"Сегодня: {now:%d %B %Y года}")
Метод str.format()
До f-строк основным способом форматирования был метод format():
# Positional arguments
print("Привет, {}!".format("Мир")) # Привет, Мир!
print("{0} + {1} = {2}".format(2, 3, 5)) # 2 + 3 = 5
print("{0} и {0}".format("Python")) # Python и Python
# Named arguments
print("Имя: {name}, Город: {city}".format(
name="Иван",
city="Москва"
))
# Format spec with format()
print("{:>10}".format("test")) # ' test'
print("{:.2f}".format(3.14159)) # '3.14'
# Accessing attributes and items
data = {"name": "Иван", "age": 25}
print("Имя: {name}, Возраст: {age}".format(**data))
# Useful for reusable templates
template = "Файл {filename}: {size:,} байт"
print(template.format(filename="data.csv", size=1048576))
# Файл data.csv: 1,048,576 байт
Template strings (Python 3.14 -- PEP 750)
Python 3.14 вводит template strings с префиксом t"" для безопасного шаблонирования:
# Template strings - new in Python 3.14
from string import templatelib
name = "Иван"
# t-string creates a Template object, not a string
tmpl = t"Привет, {name}!"
print(type(tmpl)) # <class 'string.templatelib.Template'>
# Template can be processed safely before becoming a string
# Useful for SQL, HTML, etc. where injection is a concern
# Example: safe HTML rendering
def html_escape(template) -> str:
"""Process template with HTML escaping."""
parts = []
for item in template:
if isinstance(item, str):
parts.append(item)
else:
# Escape interpolated values
escaped = str(item.value).replace("&", "&").replace("<", "<")
parts.append(escaped)
return "".join(parts)
user_input = '<script>alert("XSS")</script>'
safe_html = html_escape(t"<p>Комментарий: {user_input}</p>")
# <p>Комментарий: <script>alert("XSS")</script></p>
Форматирование таблиц
# Simple table with f-strings
headers = ["Имя", "Возраст", "Город"]
rows = [
("Иван", 25, "Москва"),
("Мария", 30, "Петербург"),
("Алексей", 28, "Казань"),
]
# Header
print(f"{'Имя':<15} {'Возраст':>7} {'Город':<15}")
print("-" * 40)
# Rows
for name, age, city in rows:
print(f"{name:<15} {age:>7} {city:<15}")
# Output:
# Имя Возраст Город
# ----------------------------------------
# Иван 25 Москва
# Мария 30 Петербург
# Алексей 28 Казань
Красивый вывод с pprint
from pprint import pprint
data = {
"users": [
{"id": 1, "name": "Иван", "roles": ["admin", "user"]},
{"id": 2, "name": "Мария", "roles": ["user"]},
],
"total": 2,
"page": 1,
}
pprint(data, width=60, sort_dicts=False)
Работа с файлами (ввод/вывод)
# Writing to a file
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Первая строка\n")
f.write("Вторая строка\n")
print("Третья строка", file=f) # print() can write to files
# Reading from a file
with open("output.txt", "r", encoding="utf-8") as f:
content = f.read() # Read entire file
print(content)
# Read line by line (memory efficient)
with open("output.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # strip() removes trailing newline
# Read all lines into a list
with open("output.txt", "r", encoding="utf-8") as f:
lines = f.readlines() # ['Первая строка\n', 'Вторая строка\n', ...]
Вывод в stderr и логирование
import sys
import logging
# Print to stderr
print("Ошибка!", file=sys.stderr)
# Basic logging (preferred over print for production)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logging.debug("Отладочное сообщение") # Not shown (level < INFO)
logging.info("Информация") # 2026-03-30 ... [INFO] Информация
logging.warning("Предупреждение") # 2026-03-30 ... [WARNING] Предупреждение
logging.error("Ошибка") # 2026-03-30 ... [ERROR] Ошибка
Итоги
input()всегда возвращает строку -- конвертируйте явно- f-строки -- предпочтительный способ форматирования (быстрый, читаемый)
- Оператор
=в f-строках удобен для отладки:f"{x = }" - Спецификаторы формата: выравнивание, точность, проценты, даты
- Template strings (t"") в Python 3.14 -- безопасное шаблонирование
- Всегда указывайте
encoding="utf-8"при работе с файлами - Используйте
loggingвместоprint()в production-коде