Search
You exceeded the request by
0 characters

8. Formatting strings in Python

The test was not passed
0
0

Summary

- Python has various ways to format strings.

- Formatting methods include using the % operator, the format() method, or f-strings.

- The format() method allows you to output the result in columns and round floating-point numbers.

- F-strings are faster and more convenient than the format() method.

- You can specify parameter names in the f-lines and list them in any order.

- Python has a feature of combining string literals, which makes the code more readable.

Introduction

In the previous lesson We have reviewed the main types of data. Now let's take a closer look at working with strings in Python.

Sometimes there are situations when different data needs to be inserted into the string template. Yes, this can be done by simply combining data and strings, but we'll look at another way. There are several ways to do this:

  • using the % operator is an outdated option;
  • method format();
  • the newest way: f-strings.

Let's look at an example using the format() method to format strings:

Example (python)
a = "IP: {}".format('192.168.0.1')
print(a) # => IP: 192.168.0.1 

A special sequence of characters {} is used to indicate the place where the value will be inserted. One pair of curly braces for one substitution. The values that are substituted can be of different types, for example:

Example (python)
a = "List: {}".format([1, 2, 3])
print(a)        

Using the format() method, you can output the result in columns. Let's take an example:

Example (python)
a, b, c = 100, 300, 1000000
result = '{:>15} {:>15} {:>15}'.format(a, b, c)
print(result) 

Let's get distracted. Pay attention to the first line. This line will be equivalent, but more compact, to this code:

Example (python)
a = 100
b = 300
c = 1000000        

Therefore, in Python, it is very easy to exchange the values of two variables in this way:

Example (python)
d = 5
e = 10
d, e = e, d

print(d) # => 10
print(e) # => 5       

Let's go back to the example of displaying data in columns of the same width. This time we specified the column width in curly brackets {}. The > symbol indicates that the alignment is performed on the right edge (< - on the left edge and ^ - alignment in the center). You can use formatting to round floating point numbers:

Example (python)
result = '{:.1f}'.format(0.1556)
result # => 0.2 

To convert numbers to binary format, the b flag is specified after the column width.

Example (python)
result = '{:8b} {:8b} {:8b} {:8b}'.format(192, 168, 0, 1)
result # => 11000000 10101000        0        1 

Or, if necessary, fill in the empty spaces with zeros:

Example (python)
result = '{:08b} {:08b} {:08b} {:08b}'.format(192, 168, 0, 1)
result # => 11000000 10101000 00000000 00000001 

For greater clarity, you can set parameter names in the template and list them in any order:

Example (python)
result = '{ip}/{mask}'.format(mask = '24', ip = '192.168.1.1')
result # => 192.168.1.1/24 

Or just specify the argument number:

Example (python)
result = '{1}/{0}'.format('24', '192.168.1.1')
result # => 192.168.1.1/24 

Other options for formatting strings using the format() method can be found in the documentation.

Formatting with f-strings

Let's consider the most recent (at the time of writing the lesson) way of formatting strings: using f-strings.

F-strings work faster and, most often, they are more convenient to use. It looks like a regular string, but there is an f character in front of the quotation mark. And curly brackets indicate the name of the variable whose value needs to be substituted.:

Example (python)
mask, ip = '24', '192.168.1.1'
result = f'{ip}/{mask}'
result # => 192.168.1.1/24 

Note that variables must be initialized before they are used in the template, otherwise there will be an error. In addition to substituting variable values in curly brackets, you can specify the same flags through a colon as when using the format() method:

Example (python)
mask, ip = '24', '192.168.1.1'
result = f'{ip:>20}/{mask}' 

Unfortunately, many topics have not been covered yet, so in this lesson it was not possible to reveal all the possibilities of formatting strings in Python. We will return to this issue later.

Combining string literals

Python has an interesting feature: combining string literals, for example:

Example (python)
str = 'Hello' 'world'
str # => Helloworld 

Or you can wrap it on different lines, but the lines must be placed in parentheses:

Example (python)
str = ('Hello'
	   'world')
str # => Helloworld 

When we get to regular expressions in Python, you will understand what convenience this feature provides. This will make the code more readable.

In this lesson, we figured out how to format strings to increase the readability of the code and got acquainted with f-strings.

In the next lesson we will continue to study the conditional construction of if, which we previously changed the progress of the program.

Test task

Two seconds...
For the first time on the Codebra website?

Sorry about this pop-up, they annoy me too.

The codebra.ru educational resource is entirely dedicated to programming and computer security. All courses and lessons are on the main page. For the sake of interest, you can look at the content of courses on Active Directory Pentest, Python, HTML and CSS, JavaScript, C++ and others posted on the main page.

If you haven't found something, then use the site search, which is located on the main page at the very top.

Good luck learning!

Close the window