String Methods
format()
Fill replacement fields in text with values.
str.format(*args, **kwargs)
str.format() performs string formatting operations by substituting positional and keyword arguments into replacement fields delimited by curly braces {}.
Parameters
| Name | Description |
|---|---|
| *args | Values used by numbered or empty replacement fields. |
| **kwargs | Named values used by named replacement fields. |
Returns
A new formatted string.
Try it
Run it and change it
template = "Hello, {}!"
print(template.format("Sam"))
Worth knowing
- f-strings vs format(): In modern Python, f-strings (
f'{var}') are generally preferred for inline readability, butstr.format()remains essential for reusable template strings.