This article is participating in Python Theme Month. See the link for details

The beginning of everything

Let Python Learner say hello to the world. Python is the first programming language I learned, and this sentence is my “mother” in programming language learning:

# Python 2
print "Hello, world!"

# Python 2 was taught in school, but the following Python 3 statements should be used more often:
print("Hello, world!")
Copy the code

Just like the Abandon of the English word, the first thing we contact is often the most cordial and the most talked about. A simple Hello world, however, contains two strings and output that would take more than three days and nights to explain. In fact, when you see Python’s greeting to the world on the screen, you’ve already achieved success with strings.

In real development, however, you can’t just keep Python babbling, and you’ll need to fill strings with the information contained in some variables. Although Python provides a complete conversion system that allows you to convert variables into strings and then concatenate them with context, in this case it is recommended to generate the target string in a formatted manner so as not to torture yourself or the reader of the code.

The following lists three string formatting methods in Python, along with code that can be executed directly using Hello World output as an example. So, let’s get started 🙂

Note: Python 3 is used here

Initial formatting: %

The first method is the original in Python, known as %-formatting. Along with explaining the use of this tag, I’ll briefly cover the basic functions of string formatting.

The basic use of the % flag is to mark the variables to be formatted as %[option]< letter > in a string, followed by % < variable > at the end of the string, that is:

If there is only one variable, write it as:
"Above %[option]< letter > below"% < variable ># If there are more than one variables, write:
"Above %[option 1]< letter 1> middle 1 %[option 2]< letter 2> middle 2..."(< % variable1>, < variables2>,...).Copy the code

The letters at each point indicate the format in which the following variable should replace the markup in the string. %s represents a string, %d represents an integer, and %f represents a floating point. These three are more commonly used, and more complete meanings are tabulated at the end of this section.

If you feel confused here, it doesn’t matter, let’s practice it!

string

Now, if you want Python to not only say hello to the world, but to specify a name, Python can say hello to the specified person. This feature is very simple to implement, just write it like this in the form mentioned above:

name = 'Li Hua'

# Heartless hello machine
print('Hello, %s! ' % name)

Output: Hello, Li Hua!
Copy the code

In the above statement, the variable after % replaces the % + part of the preceding string and prints it, equivalent to ‘Hello, ‘+ name + ‘! ‘, of course, the latter is possible thanks to Python’s powerful string handling mechanisms.

Floating point and integer

Further, if you’re greeting a friend and need to tell him or her something digital, such as the price of a shirt, then use integer %d and floating point %f. The calculation can also be done in the output step.

name = 'Li Hua'
price = 9.15
n = 2

# Li Hua, the price of the shirt is 9 pounds 15 pence, two pieces are £18.30!
s = 'Hello, %s! The price of The shirt is £%.2f. So % D shirts will cost you £%. % (name, price, n, n*price)

print(s)
Output: Hello, Li Hua! The price of The shirt is £9.15. So 2 shirts will cost you £18.3.
Copy the code

There are four % tags, so there should be an equal number of variables in the final tag area, and these variables should be filled in the corresponding positions according to the format of the tags. If you look closely at %.2f, in the original format,.2 is the so-called option. This option indicates that two decimal places are reserved. The number of decimal places is reserved, following the rounding principle.

A placeholder

In addition to normalizing the output itself, this option can also normalize the width of the entire insert result, and if the converted result is not wide enough, it will be filled out with placeholders. This width is represented as a number, inserted in the options described above (floating point format before the decimal point), such as %3s, %4d, and %6.2f. In particular, integers and floating-point types can use 0 as a placeholder. This can be done by prefacing % and the width number with 0.

# string with Spaces as placeholders
s = 'world'
print('Hello,%s.\nHello,%6s! ' % (s, s))
The second line of output will have one more space than the first line.

# Integer with space or 0 as placeholder
num = 4.525
print('Spaces%6dhere and zeros%03dhere' % (num, num))
Spaces 4here and zeros004here

# floating point number with space or 0 as placeholder
print('Spaces % 6.2 fhere and zeros % 07.1 fhere' % (-num, -num))
Spaces -4.53here and Zeros-0004.5 here
# note that the width is calculated with a decimal point and a minus sign, and note the position of the minus sign
Copy the code

% summary

Well, by now you have a general idea of Python formatting output, especially %-formatting. Simply put, Python formats a string by reserving a place for a variable in a string and filling it with its value in some format.

The following table lists the types of tags that % can provide, the options, and examples. Of course, this is not a comprehensive list, but see this link for a more comprehensive list of formats.

tag meaning options The sample
%s string <num>: The total width should not be less than, the insufficiency should be filled with Spaces '%12s' % 'hello'= >7*' '+'hello'
%d Decimal integer <num>%S;0<num>Again, the total width is not less than, but the insufficiency is filled with ‘0’ '%5d %07d'%(123, 442)= >'123 0000442'
%f Floating point [0]<num1>.<num2>: same before the decimal point%dThe part after the decimal point indicates the number of decimal places to be reserved, rounded. '% 03.2 f % 123.444= >'123.44'
%e / %E E/E stands for scientific notation with%f 010.2 e % % 12363= >'001.24 e+10'
%o Octal integer with%d '%05o' % 100= >'00144'
%x / %X A hexadecimal integer, x indicates lowercase letters, and x indicates uppercase letters with%d '%04x' % 108= >'006c';'%04X' % 108= >'006C'

‘{}’.format()

With a general understanding of Python formatting, let’s talk about other formatting methods. The biggest problem with the % method is that it is not very readable. Once the % method is more than %, you have to go back and forth, which is very troublesome. Another common format method, format(), solves this problem.

This function, introduced in version 2.6, is called as a method of Python’s built-in string class by appending the string with.format(). It is used with {} in the string. {} can be understood as % in the previous section. The format() function replaces the {} in the string with the given format, for example:

print('Hello, {}! '.format('world')) # output Hello, world!
Copy the code

advantage

With the foundation of the previous section, it is not difficult to understand this one. Format () provides a more comfortable indexing mechanism than %. To be specific:

  1. Variables can be indexed by numbers

Look at the following example:

# Hello World
name0 = 'world'
name1 = 'Li Hua'

print('Hello, {0}! Hello, {1} and hello {0} again! '.format(name0, name1))
Output: Hello, world! Hello, Li Hua and hello world again!
Copy the code

You’ll see that all {0} is replaced with name0, and all {1} is replaced with name1. The index in curly braces corresponds to the argument passed in the format function later.

  1. You can set parameters

This approach brings the format up a notch in readability. We can add a custom parameter name to each curly brace, and then specify the value of each parameter. Li Hua, I want to buy a shirt.

# variable
name = 'Li Hua'
price = 9.15
n = 2

# dialogue
s = 'Hello, {name}! The price of the shirt is £{price}. So {n} shirts will cost you £{total}.'.format(name=name, price=price, n=n, total=n*price)

print(s)
Output: Hello, Li Hua! The price of The shirt is £9.15. So 2 shirts will cost you £18.3.
Copy the code

It feels a bit like a cloze, giving you hints about what to fill in each blank. As long as the variables are named the way they should be, there is no need for anyone else to read the string. Format (…) You can get a sense of what this sentence means.

  1. Good compatibility with dictionaries, lists, and classes

For this, look at the following example code:

# dictionary
my_dict = {"name":"Li Hua"."price": 9.15}
# ** indicates disassembly
print("Hello, {name}! The price of the shirt is {price}".format(**my_dict))

# list
my_list1 = ["Li Hua".9.15]
my_list2 = [2.2*9.15]
# 0[0] The first 0 represents the list
print("Hello, {0[0]}! The price of the shirt is £{0[1]}. So {1[0]} shirts will cost you £{1[1]}.".format(my_list1, my_list2))

# class & object
class Shopping:
    def __init__(self, name, price, num) :
        self.name = name
        self.price = price
        self.num = num
        self.total_cost = num * price
    
lihua_shopping = Shopping('Li Hua'.9.15.3)
{0. Name} {0.
print("Hello, {0.name}! The price of The shirt is £{0. Price} So {0. Num} shirts will cost you £{0..format(lihua_shopping))
Copy the code

Digital format

You may have noticed {0. Total_cost :.2f} on the last line, which is the formatting option provided by the format function. Options are enclosed in braces, after an index or variable, separated and joined by:. For example, {:.2f} means to keep two decimal places, {0>2d} means to fill the left side with 0 to the integer width of at least 2, {:.2%} means to keep the percentage of two decimal places, and so on. Detailed parameter table in the rookie tutorial, I here steal a lazy, do not write ~

f-strings

This formatting method is younger. It was introduced in version 3.6 and has the full functionality of the first two formatting methods while being more concise in presentation. For example, if we define name=’world’, we just need to add an f to the string and insert the variable name inside {} :

print(f'Hello, {name}! ')
Copy the code

Type this simple sentence and it will appear Hello, World! .

Use the sample

This expression uses a string tag similar to format, but it does not specify the values of these variables. In fact, the {} part of f-Strings can be directly understood as a Python statement, because it can be not only a variable, but also an expression, a function, an object, and any statement that returns a string can be placed here.

M: Hey, li Hua, if n=1, the shirt should be singular. This can be easily solved with f-strings, and the calculation of the price can also be included in the string:

s = f'Hello, {name}! The price of the shirt is £{price}. So {n} shirt{(n>1) *"s"}Will cost you £{n*price}. '

print(s)
Copy the code

If there is a defined function, it can be called directly from f-strings:

def square(n) :
    """ "Square """
    return n*n

n = 3
print(f'{n}The square is{square(n)}. ')
Output: 3 squared is 9.
Copy the code

Even if you define __str__ for a class, you can insert the class’s object directly into the curly braces for F-strings:

class Student:
    def __init__(self, name, id_num) :
        self.name = name
        self.id_num = id_num
        
    def __str__(self) :
        return f"Name: {self.name}, ID: {self.id_num}"


lihua = Student('Li Hua'.'20210713')
print(f"Following is the info of the student:\n{lihua}.")
# {lihua} corresponds to {STR (lihua)}
Copy the code

Please stamp

Similarly, f-strings can format the output for numbers, separated by:, just like format. This point is quite similar to the format. I found a detailed document from the official website of Bentley University. If you are interested, you can read it.

In addition, F-strings is not only simple in expression, but also runs faster than the previous two methods. Therefore, f-Strings formatting is highly recommended as long as the Python version is supported.

Write in the last

The evolution of Python’s three formats also gives a glimpse of what developers need in a programming language: readability. From inserting arguments sequentially to embedding Python expressions directly in strings, Python formatting is becoming more approachable. There’s a really interesting quote I came across in a book called Practial Vim, which is more appropriate than too extreme:

Code is first to be seen and second to be run.

Finally, I hope this article has been helpful in your Python learning process. ❤

Refer to the link

Python Basics _ Formatting Output (% usage and Format Usage) – RuiWo – Blogpark (cnblogs.com)

The Python string | novice tutorial (runoob.com)

Python format format function | novice tutorial (runoob.com)

Python Formatting string f-strings – Catch up with newbies – Cnblogs.com

A Guide to f-string formatting in Python – Bentley Univ.