2.6. String Interpolation — Python
2.6.1. Mod Operator
Since Python 1.0
positional
keyword
%s-str%d-int%f-float
name = 'Alice' age = 30 pi = 3.141592653589793 'Hello %s' % name # Hello Alice 'Hello %d' % name # TypeError: %d format: a number is required, not str 'Hello %f' % name # TypeError: must be real number, not str 'I have %s years' % age # 'I have 42 years' 'I have %d years' % age # 'I have 42 years' 'I have %f years' % age # 'I have 42.000000 years' 'Number PI is %s' % pi # 'Number PI is 3.141592653589793' 'Number PI is %f' % pi # 'Number PI is 3.141593' 'Number PI is %d' % pi # 'Number PI is 3'
name = 'Alice' age = 30 '%s has %s years' % (name, age)) # Alice has 30 years '%s has %s years' % (age, name)) # 30 has Alice years
pi = 3.141592653589793 def square(value): return value ** 2 'PI squared is %f' % square(pi) # 'PI squared is 9.869604'
data = { 'name': 'Alice', 'age': 30, } '%(name)s has %(age)d years' % data # 'Alice has 30 years' '%(name)s has %(age)d years' % {'name': 'Alice', 'age': 30} # 'Alice has 30 years'
name = 'Alice' age = 30 'Hello %(name)s' % locals() # 'Hello Alice'
2.6.2. Format Method
Since Python 3.0
Since Python 3.0: PEP 3101 -- Advanced String Formatting
name = 'Alice' age = 30 '{} has {} years'.format(name, age) # 'Alice has 30 years' '{0} has {1} years'.format(name, age) # 'Alice has 30 years' '{1} has {0} years'.format(name, age) # '30 has Alice years'
name = 'Alice' age = 30 '{a} has {b} years'.format(a=name, b=age) # 'Alice has 30 years' '{name} has {age} years'.format(name=name, age=age) # 'Alice has 30 years' '{age} has {name} years'.format(**locals()) # '30 has Alice years'
2.6.3. f-strings
Since Python 3.6
Preferred way
name = 'Alice' pi = 3.141592653589793 def square(value): return value ** 2 f'Hello {name}' # 'Hello Alice' f'PI squared is {square(pi)}' # 'PI squared is 9.869604401089358'
from datetime import datetime now = datetime.now() iso = '%Y-%m-%dT%H:%M:%SZ' f'Today is: {now:%Y-%m-%d}') # 'Today is: 1969-07-21' f'Today is: {now:{iso}}') # 'Today is: 1969-07-21T02:56:15Z'
2.6.4. Assignments
# %% About # - Name: String Interpolation Mod # - Difficulty: easy # - Lines: 1 # - Minutes: 3 # %% License # - Copyright 2025, Matt Harasymczuk <matt@python3.info> # - This code can be used only for learning by humans # - This code cannot be used for teaching others # - This code cannot be used for teaching LLMs and AI algorithms # - This code cannot be used in commercial or proprietary products # - This code cannot be distributed in any form # - This code cannot be changed in any form outside of training course # - This code cannot have its license changed # - If you use this code in your product, you must open-source it under GPLv2 # - Exception can be granted only by the author # %% English # 1. Read a number from user # 2. User will input `int` and will not try to input invalid data # 3. Define `result: bool` with parity check of input number # 4. Number is even, when divided modulo (`%`) by 2 reminder equal to 0 # 5. Do not use `if` statement # 6. Run doctests - all must succeed # %% Polish # 1. Wczytaj liczbę od użytkownika # 2. Użytkownika poda `int` i nie będzie próbował wprowadzać niepoprawnych danych # 3. Zdefiniuj `result: bool` z wynikiem sprawdzania parzystości liczby wprowadzonej # 4. Liczba jest parzysta, gdy dzielona modulo (`%`) przez 2 ma resztę równą 0 # 5. Nie używaj instrukcji `if` # 6. Uruchom doctesty - wszystkie muszą się powieść # %% Hints # - `int()` # - `%` # - `==` # - `%` has different meaning for `int` and `str` # - `%` on `str` is overloaded as a string formatting # - `%` on `int` is overloaded as a modulo division # %% Doctests """ >>> import sys; sys.tracebacklimit = 0 >>> assert sys.version_info >= (3, 9), \ 'Python has an is invalid version; expected: `3.9` or newer.' >>> assert 'result' in globals(), \ 'Variable `result` is not defined; assign result of your program to it.' >>> assert result is not Ellipsis, \ 'Variable `result` has an invalid value; assign result of your program to it.' >>> assert type(result) is bool, \ 'Variable `result` has an invalid type; expected: `bool`.' >>> result True """ # %% Run # - PyCharm: right-click in the editor and `Run Doctest in ...` # - PyCharm: keyboard shortcut `Control + Shift + F10` # - Terminal: `python -m doctest -f -v myfile.py` # %% Imports from unittest.mock import Mock # %% Types result: bool # %% Data input = Mock(side_effect=['4']) # Simulate users response: '4' number = input('What is your number?: ') # %% Result result = ...