10.1 format()
We often need to output a lot of data to the console (on the screen). We're definitely not the first to deal with this — which is why Python has
had the function format()
for a while now, and it lets you
combine strings and display data on the screen way easier and more understandably.
The format()
function is used to insert values into
a string at specific positions. The syntax of the function looks like this:
"String template from {} to {}".format(value1, value2,…)
Fact 1. The function format()
— is a string
method, so it's called on a string. Instead of passing a string to the function, we write the string, put a dot, and
then call the format()
function, passing its parameters into it.
Fact 2. The function format()
fills the
string template with the passed values. It converts passed
values into strings (if there were numbers, for example) and inserts them into
places marked by {}
. Such a place for inserting a value is called a placeholder
.
Basic usage:
welcome_message = "Hello, {}, welcome to {}!"
print(welcome_message.format("Anna", "our store"))
Result:
"Hello, Anna, welcome to our store!"
Number formatting:
output = "Data: {0:.2f} and {1:.2f}".format(3.1415926, 2.71828)
print(output)
Result: "Data: 3.14 and 2.72"
—
demonstrating output restricted to two decimal places.
Using keywords:
output = "{name} works at {company}"
print(output.format(name="Sergey", company="Google"))
Result:
"Sergey works at Google"
Using format()
enhances the readability and
maintainability of the code, allowing you to easily change the format without
having to edit the entire string.
10.2 f-notation
Starting with version 3.6, Python introduced a new type of string — f-strings
,
which literally mean "formatted string". These strings improve the
readability of the code and run faster than other formatting methods.
To use f-strings
, just put the letter
"f"
or "F"
before a string. Expressions to embed
are placed in curly braces {}
:
Example:
force = "Dark Side"
message = f"May the force be with you {force}!"
print(message) # Outputs: May the force be with you Dark Side!
Note! Inside the curly brackets, you can include variables that are accessible in the current scope (more on that later) and Python will automatically convert them to a string and put them in the desired location.
Example:
age = 28
message = f"I am {age} years old"
print(message) # Outputs: I am 28 years old
Plus, you can use expressions with a bunch of variables inside the curly brackets.
Example:
birth_year = 1985
current_year = 2024
message = f"I am {current_year - birth_year} years old"
print(message) # Outputs: I am 39 years old
Under the hood, it all gets converted to a call to
format()
, but the new approach is really more convenient.
Enjoy using it to your heart's content.
10.3 Parameters sep
and end
In Python, the function print()
offers
two handy parameters — sep
and end
,
which allow you to control the output of data. These parameters make
the print()
function more flexible and can be used
for output formatting without needing additional functions or complex string operations.
The parameter sep
defines the character or
string that will be used to separate multiple values passed to print()
. By default, sep
is set as a space. This means if you pass
multiple arguments to print()
, they'll be separated
by a space.
But if you want the data to be separated by, for instance, a comma, just add the parameter
sep
at the end and
immediately assign it a new separator string.
Example:
print("Hello", "world") # Output: Hello world
print("Hello", "world", sep=", ") # Output: Hello, world
Or, for example, you can make each value appear on a
new line. Then, assign the sep
parameter
the special newline character — denoted by “\n”
.
Example | Explanation |
---|---|
|
|
The parameter end
defines what will be printed after all the passed
values. The default value for end
is the newline character (\n)
, meaning it moves to a new line after executing print()
.
By changing end
, you can control how data is printed, for instance,
to continue output on the same line:
Example:
print("Hello", end=" ")
print("world") # Output: Hello world
Using sep
and end
can be incredibly useful in scenarios where specific
output formatting is required, such as creating tables, reports, or when showing data in a single line without
auto-line-breaks.
Aside from simplifying the code and avoiding the need to manually add separators or manage line breaks,
using sep
and end
improves the readability and maintainability of the code.
GO TO FULL VERSION