The% notation using the% operator has long been used to embed variables in strings in Python, but since Python 2.6 there has been a new alternative. That's how you use the "format function" to embed variables in a string. This time, I will explain how to use the "format function".
Table of contents [Hide] 1 [What is the format function? ](What is the ## format function?) 2 [format function syntax](## format function syntax) 2.1 [Give multiple arguments](### Give multiple arguments) 2.2 [Embed list or tuple](### Embed list or tuple) 3 [Format function](## Format function format) 3.1 [How to specify the format](### How to specify the format) 3.2 [Numerical representation](### Numerical representation) 3.3 [Width](### Width)
The format function is used by Pyhon to embed a variable in a string. Especially, it is used when you want to output a variable with an arbitrary character string with the print function. The basic syntax of the format function is as follows.
'Arbitrary string{}Arbitrary string'.format(variable)
In the argument of the format function, put the variable you want to embed in the string. Then, the variable is embedded in the part with {}. This allows you to output variables and strings together. For example, it is possible to assign the calculation result to a variable, add a unit with a character string, and then output it.
apple = 50
orange = 100
total = apple + orange
print('total:{}Circle'.format(total))
Execution result
Total: 150 yen
Now you know what the format function looks like. Let's take a closer look at the syntax of the format function.
You can pass multiple variables as arguments to the format function and embed them in a string. When embedding multiple variables, you need to specify which argument to embed in which {}, but there are several ways to specify it. The following specification methods are typical.
'{0}, {1}, {2}...'.format(Variable 1,Variable 2,Variable 3 ....) #Specified by index (subscript)
'{h1}, {h2},{h3}..'.format(h1=Variable 1, h2=Variable 2, h3=variable…) #Specified by keyword argument
'{h1},{h2},{h3}…'.format(**{'h1':Variable 1, 'h2':Variable 2, 'h3':Variable 3 ....} ) #Specified in dictionary
"Specify by index" is a method to specify the variable to be embedded in {} by describing the number of the argument of the format function in {} as an index.
"Specify by keyword argument" is a method of giving a name to the argument and specifying it by that name. You have to give each argument a name, but it has the advantage that the result does not change even if the order of the arguments changes. "Specify with dictionary" is the same as the method of specifying with keyword arguments, but the arguments are named using the dictionary type.
You can embed multiple arguments with any method, but basically "specify by index" is simple and easy to use.
apple = 50
orange = 100
total = apple + orange
print('Apple:{0}Yen mandarin orange:{1}Yen total:{2}Circle'.format(apple, orange, total))
Execution result
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen
You can also embed sequence-type variables such as lists and tuples using the format function. Embed list and tuple elements by writing the subscripts of list and tuple elements in {}.
'{0[Suffix]}, {0[Suffix]}, {1[Suffix]}, {1[Suffix]}…'.format(Listing 1,Listing 2 ....)
The number to the left of {0 [subscript]} indicates the number of the argument of the format function (in this case, a list or tuple) to be embedded in {}, and [subscript] is displayed in that variable. It is the index of the element you want. For example, {0 [1]} represents the first element of the 0th argument.
apple = 50
orange = 100
total = apple + orange
list = [apple, orange, total] #Creating a list
print('Apple:{0[0]}Yen mandarin orange:{0[1]}Yen total:{0[2]}Circle'.format(list))
Execution result
Apples: 50 yen Mandarin oranges: 100 yen Total: 150 yen
When you use the format function to embed a variable in a string, you can specify its format. There are so many types of formats that I can't cover all of them, but here are some of the most commonly used ones.
If you want to specify the format and embed it, do as follows.
'{0:The type of format you want to specify}'format(variable)
You can specify the format by writing: in {} and the type of the format you want to specify on the right side.
In addition to the decimal numbers we usually use, there are other numbers such as binary numbers and hexadecimal numbers. If you want to embed in decimal numbers, you do not have to specify it, but if you want to embed in other decimal numbers, specify the format.
Model name | Description |
---|---|
b | Output in binary |
d | Output in decimal |
o | Output in octal |
x | Output in hexadecimal |
X | Output in hexadecimal |
decimal = 106
print('{0}Is a binary number{0:b}, In octal{0:o}, In hexadecimal{0:X}'.format(decimal))
Execution result
106 is 1101010 for binary, 152 for octal, 6A for hexadecimal
When embedding a variable in a string with the format function, you can also specify the width and display position when embedding.
Model name | Description |
---|---|
<Arbitrary width | Arbitrary widthを取り、左詰め |
>Arbitrary width | Arbitrary widthを取り、右詰め |
^Arbitrary width | Arbitrary widthを取り、中央寄せ |
You can use the space key to enter the width in advance, but if you specify it with a number, you can see how wide it is and the source code will be cleaner.
string1 = 'Left justified'
string2 = 'Centered'
string3 = 'Right justified'
print('{0:<10}'.format(string1))
print('{0:^10}'.format(string2))
print('{0:>10}'.format(string3))
Execution result
Left justified
Centered
Right justified
Reference site [Introduction to Python] How to write a character string with the format function
Recommended Posts