[Introduction to Python] How to write a character string with the format function

[Introduction to Python] How to write a character string with the format function

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)

What is the format function?

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

format function syntax

Now you know what the format function looks like. Let's take a closer look at the syntax of the format function.

Give multiple arguments

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

Embed lists and tuples

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

format function specification

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.

How to specify the format

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.

Numerical representation

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

width

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

[Introduction to Python] How to write a character string with the format function
[Introduction to Python] How to split a character string with the split function
[Introduction to Python] How to iterate with the range function?
[Introduction to Python] How to get data with the listdir function
[Python] How to invert a character string
[Introduction to Python] How to output a character string in a Print statement
[Python] Explains how to use the format function with an example
[Python] Explains how to use the range function with a concrete example
[Introduction to Python] How to sort the contents of a list efficiently with list sort
[Introduction to Python] How to get the index of data with a for statement
How to write a Python class
Python learning basics ~ How to output (display) a character string? ~
[Python 3.8 ~] How to define a recursive function smartly with a lambda expression
Try to extract a character string from an image with Python3
[Introduction to Python] How to use the in operator in a for statement?
How to extract the desired character string from a line 4 commands
[ROS2] How to play a bag file with python format launch
How to send a request to the DMM (FANZA) API with python
How to quickly count the frequency of appearance of characters from a character string in Python?
The 16th offline real-time how to write problem was solved with Python
How to read a CSV file with Python 2/3
How to embed a variable in a python string
Summary of character string format in Python3 Whether to live with the old model or the new model
How to create a function object from a string
Think about how to write a filter with the Shotgun API-Contact Versions
[Python] How to change the date format (display format)
[Introduction to Udemy Python3 + Application] 47. Process the dictionary with a for statement
The 16th offline real-time how to write reference problem to solve with Python
Introduction to Python with Atom (on the way)
How to write a string when there are multiple lines in python
The 19th offline real-time how to write reference problem to solve with Python
The 15th offline real-time how to write problem was solved with python
[Introduction to Python] Thorough explanation of the character string type used in Python!
[Go] How to write or call a function
I want to write to a file with Python
How to input a character string in Python and output it as it is or in the opposite direction.
[Circuit x Python] How to find the transfer function of a circuit using Lcapy
[Tentative] How to convert a character string to Shift_jis with kivy-ios Memo kivy v1.8.0
[Python] I tried to get the type name as a string from the type function
How to get a list of files in the same directory with python
How to write a GUI using the maya command
How to delete the specified string with the sed command! !! !!
[Python] How to draw a line graph with Matplotlib
How to write string concatenation in multiple lines in Python
How to create a submenu with the [Blender] plugin
[Python] How to specify the download location with youtube-dl
How to write a list / dictionary type of Python3
# Function that returns the character code of a string
I want to split a character string with hiragana
[Python] How to write a docstring that conforms to PEP8
[Python] A memo to write CSV vertically with Pandas
A program to write Lattice Hinge with Rhinoceros with Python
[Introduction to Udemy Python3 + Application] 30. How to use the set
[Introduction to Python] How to stop the loop using break?
[Python] How to rewrite the table style with python-pptx [python-pptx]
[Python] How to create a 2D histogram with Matplotlib
[Introduction to Python] How to write repetitive statements using for statements
[Python] How to call a c function from python (ctypes)
[Python] How to draw a scatter plot with Matplotlib
How to call a function
Write to csv with Python