Starting from Hello world, Python's string formatting

The beginning of everything

The first thing every Python Learner learns is to let Python say hello to the world. I am very impressed by this sentence, because Python is the programming language I first came into contact with. This sentence is also my "mother" in learning programming language:

# Python 2
print "Hello, world!"

# Python 2 is taught in school, but in fact, the following Python 3 statements should be more commonly used:
print("Hello, world!")

Like Abandon in English words, the things we first contact are often the most cordial and most talked about. However, the simple sentence Hello world contains two things behind it: string and output, which can't be finished in three days and nights. In fact, when you see Python's greetings to the world on the screen, you have successfully used the string.

However, in the actual development, we certainly can't let Python just babble like this. Instead, we need to fill the information contained in some variables into the string according to certain requirements. Although Python provides a complete type conversion system, which allows you to convert variables into strings and then connect them with the context, in order not to torture yourself or code readers, it is recommended to generate the target string in a formatted way.

Three string formatting methods in Python are listed below. At the same time, the code that can be executed directly will be given by taking the output related to Hello world as an example. So let's start:)

Note: Python 3 is used here

Format:%

The first method is the earliest in Python, namely% - formatting. While explaining the usage of this tag, I will also briefly introduce the basic functions of string formatting.

The basic usage of marking% is to mark the variables to be formatted in the form of% [options] < letters > in the string, and then add% < variables > after the whole string, that is:

# If there is only one variable, write:
"Above %[option]<letter> Below" % <variable>

# If there are multiple variables, write:
"Above %[Option 1]<Letter 1> Middle 1 %[Option 2]<Letter 2> Middle 2 ..." % (<Variable 1>, <Variable 2>, ...)

Each letter indicates the format in which the following variable should replace the tag in the string s represents string,% d represents integer and% f represents floating point. These three are commonly used. More complete mark meanings will be listed in a table at the end of this section.

If you feel confused here, it doesn't matter. Let's practice it!

character string

If you want Python to not only say hello to the world, but specify a name, python can say hello to the specified person. This function is very simple to implement. It can be written in the form mentioned above:

name = 'Li Hua'

# Say hello to the machine mercilessly
print('Hello, %s!' % name)

# Output: Hello, Li Hua!

In the above output statement, the variable after% will replace the% + letter in the previous string and output it, which is equivalent to 'Hello,' + name + '!', Of course, the latter can be realized thanks to Python's powerful string processing mechanism.

Floating point and integer

Further, if you need to tell ta some digital information, such as the price of shirts, on the basis of saying hello to your friends, you need to use integer% d and floating-point format% f. The calculation can also be completed in the output step.

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

# Li Hua, the price of the shirt is 9 pounds and 15 pence, 2 pieces, a total of £ 18.3!
s = 'Hello, %s! The price of the shirt is £%.2f. So %d shirts will cost you £%.1f.' % (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.

There are four% tags, so there should be the same number of variables corresponding to them in the last tag area, and these variables should be filled into the corresponding positions according to the tag format. Take a closer look at this%. 2f. According to the format at the beginning,. 2 is the so-called option. This option means to keep two decimal places. The decimal point is the number of decimal places. Follow the principle of rounding.

placeholder

In fact, the options here can not only standardize the output itself, but also standardize the width of the whole insertion result. If the conversion result is not wide enough, it will be supplemented with placeholders. This width is expressed in numbers and inserted in the above options (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 placeholders. To achieve this, you only need to add 0 before% and the number representing the width

# String with spaces as placeholders
s = 'world'
print('Hello,%s.\nHello,%6s!' % (s, s))
# The second line in the 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))
# Output: spaces 4here and zeros004here

# Floating point number with space or 0 as placeholder
print('Spaces%6.2fhere and zeros%07.1fhere' % (-num, -num))
# Output: Spaces -4.53here and zeros-0004.5here
# Note that the decimal point and minus sign are included in calculating the width here, as well as the position of the minus sign

%Summary

Well, by now, you must have a general understanding of Python's formatted output, especially% - formatting. In short, Python's format string is to reserve the position of the variable in the string, and then fill in the value of the variable in a certain format.

The following table lists% the tag types, options and corresponding examples that can be provided. Of course, the format here is not comprehensive. You can refer to a more comprehensive format list This link.

signmeaningoptionExample
%scharacter string< num >: the total width shall not be less than, and the insufficient part shall be filled in with spaces'%12s' % 'hello' => 7*' '+'hello'
%dDecimal integer< num > same as% s; 0 < num > similarly, the total width is not less than, but the insufficient part is filled with '0''%5d %07d'%(123, 442) => ' 123 0000442'
%ffloating-point[0]<num1>.< Num2 >: the part before the decimal point is the same as% d, and the part after the decimal point represents the number of decimal places to be reserved and rounded.'%03.2f' % 123.444 => '123.44'
%e / %Ee / E stands for scientific countingSame as% f'%010.2e' % 12363 => '001.24e+10'
%oOctal integerSame as% d'%05o' % 100 => '00144'
%x / %XHexadecimal integer, X for lowercase, X for uppercaseSame as% d'%04x' % 108 => '006c';'%04X' % 108 => '006C'

'{}'.format()

After we have a general understanding of Python formatting, let's talk about other formatting methods The biggest problem with marking methods is poor readability. Once% more, you have to pair from front to back, which is very troublesome. Another common formatting method, format(), can solve this problem.

This function was introduced in version 2.6 as a method of Python's built-in type string class, adding Format() can be called. It should be used with {} in the string. {} can be understood as the% mentioned in the previous section. The variables in the format() function will replace {} in the string according to the given format to realize formatting, such as:

print('Hello, {}!'.format('world')) # Output Hello, world!

advantage

With the basis of the previous section%, it must not be difficult to understand this section. format() provides a more comfortable indexing mechanism than%. Specifically:

  1. Variables can be indexed numerically

Take 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!

You will find that all {0} are replaced with name0, and all {1} are replaced with name1. The index in curly braces corresponds to the parameters passed in the format function.

  1. Parameters can be set

This way makes the readability of format a step higher. We can add a custom parameter name to each curly bracket, and then specify the value of each parameter later. Let's rewrite Li Hua's dialogue on buying shirts in the previous section to feel the improvement of readability:

# 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.

This feeling is a bit like cloze, which gives you a hint of what to fill in each blank. As long as the variable is named according to common sense, others don't need to look at the following string when looking at the string format(...) You can roughly get the meaning of this sentence.

  1. It has good compatibility with dictionaries, lists and classes

For this, just look at the following example code:

# Dictionaries
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 a 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 in {0.name} can be omitted here!
print("Hello, {0.name}! The price of the shirt is £{0.price}. So {0.num} shirts will cost you £{0.total_cost:.2f}.".format(lihua_shopping))

Digital format

You may have noticed {0.total_cost:.2f} in the last line, which is the formatting option provided by the format function. Options are in curly braces, after indexes or variables, separated by: and added. For example, {:. 2f} means to keep two decimal places, {0 > 2D} means to fill the left with 0 to an integer with a width of at least 2, {:. 2%} means to keep the percentage of two decimal places, etc. The detailed parameter table is shown in Rookie tutorial Yes, I'm lazy here, so I won't write it~

f-strings

This formatting method is younger. It was born in version 3.6. It has the complete functions of the first two formatting methods and is more concise in expression. For example, when name='world 'is defined in our Hello world, we only need to add an f in front of the string and fill in the variable name in the internal {}:

print(f'Hello, {name}!')

If you type this simple sentence, Hello, world will appear on the screen! Yes.

Use example

The in string tags used in this expression are somewhat similar to format, but it does not need to indicate the values of these variables. In fact, the {} internal component in f-strings can be directly understood as Python statements, because it can not only be variables, but also expressions, functions and objects. Any statement whose return result can become a string can be placed here.

I wonder if you have noticed a bug in Li Hua's conversation about buying shirts, that is, when n=1, the following shirt should be singular. This problem can be easily solved by using f-strings, and the price calculation 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)

If there are defined functions, they can also be called directly in f-strings:

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

n = 3
print(f'{n} The square of is {square(n)}.')
# Output: the square of 3 is 9

Even, if you define a class__ str__ , You can even insert the object of this class directly into the curly braces of 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} is equivalent to {str(lihua)}

Please stamp for details

Similarly, f-strings can also define the output format for numbers, and they are separated by: like format. This is quite similar to format. I found a more detailed article file , from the official website of Bentley University, interested partners can read it.

In addition, f-strings is not only concise, but also faster than the first two methods. Therefore, as long as the Python version is supported, it is highly recommended to use f-strings for formatting.

Write at the end

From the development and changes of the three formatting methods of python, we can also see the developers' demand for programming language, that is, readability. From sequentially inserting parameters to directly including Python expressions in strings, python formatting is becoming more approachable step by step. There is a very interesting saying that I saw in the book Practical vim. I can't say it's a little extreme, but it's very appropriate:

The code is first for people to see, and then it can run.

Finally, I hope this article can help you in learning Python. ❤

Reference link

python Foundation_ Formatted output (% usage and format usage) - RuiWo - blog Garden (cnblogs.com)

Python string | rookie tutorial (runoob.com)

Python format function | rookie tutorial (runoob.com)

python format string f-strings - chasing rookies - blog Garden (cnblogs.com)

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

Keywords: Python Back-end

Added by masteroleary on Wed, 05 Jan 2022 11:43:13 +0200