[Python] Explains how to use the format function with an example

How to use python's format function

What you can do with the format function

  1. [You can substitute the value / string defined by the argument](# 1 Substitute the value string defined by the argument)
  2. [Multiple arguments can be set](Specify multiple values for # 2 argument)
  3. [Specify by index number](#Specify by presence or absence of index number)
  4. [Can use the same argument multiple times](#Call multiple times)
  5. [Same order](when there are multiple # arguments)
  6. [Can be set with character string / numerical value / variable](# 3 Set with character string numerical variable)
  7. [Wide width](# 4 Widen width)
  8. [Left-justified, right-justified, center-justified](# 5 Specify text alignment align)
  9. [Fill in blanks](# 7 Fill in blanks)
  10. [Fill with zero](#Fill with zero)
  11. [Fill with any character](#Fill with any character)
  12. [Set comma in thousands](# Set comma in thousands)
  13. [Display% (100 times numerical value)](# 8 100 times numerical value displayed)
  14. [Add a sign to the number](# 9 Add a sign to the number)
  15. [Specify the number of decimal places](# 10 Specify the number of decimal places)
  16. [Fixed-point notation (e)](# 11 Fixed-point notation e)
  17. [Specify variable in argument](# 12 Specify variable in argument)
  18. [Convert date data to specified character string](# 13 Convert date data to specified character string)

## How to use the format function ### (1) Substitute the value / character string defined in the argument ** Basic syntax ** `{}.format(A)` └ The contents of A are in {}

Example (basic form)


'{}The weather at the station is sunny'.format('Shibuya')

#output
#'The weather at Shibuya station is sunny'

### (2) Specify multiple values for the argument `{n}.format(A,B,C,,,)` └ n: Specify the argument number (number) (from 0) └ 0 if no number is specified

Designation by presence / absence of index number

Example (no index number)


'{}The weather at the station is sunny'.format('Shibuya','Shinjuku','Mejiro','Ikebukuro')

#output
#'The weather at Shibuya station is sunny'

Example (index number 0)


'{0}The weather at the station is sunny'.format('Shibuya','Shinjuku','Mejiro','Ikebukuro')

#output
#'The weather at Shibuya station is sunny'

Example (index number 1)


'{1}The weather at the station is sunny'.format('Shibuya','Shinjuku','Mejiro','Ikebukuro')

#output
#'The weather at Shinjuku station is sunny'

Example (index number 4)


'{4}The weather at the station is sunny'.format('Shibuya','Shinjuku','Mejiro','Ikebukuro')

#output(error)
#IndexError: Replacement index 4 out of range for positional args tuple

If there is no data corresponding to the index number, an error will occur.


### Call multiple times #### One argument `{0}{0}{0},,,.format(A)` └ The argument value is entered in the installed {0}

Example (call one argument multiple times)


'{0}Weather.{0}Ward,{0}The weather at the station is sunny'.format('Shibuya')

#output
#'Shibuya weather. The weather at Shibuya Ward and Shibuya Station is sunny'

If 0 is not specified for the index number, an error will occur. Because the index number in {} is automatically set in order from 0.

Example (error case)


'{}Weather.{}Ward,{}The weather at the station is sunny'.format('Shibuya')

#output(error)
#IndexError: Replacement index 1 out of range for positional args tuple

#### When there are multiple arguments

Example (multiple arguments, no number specified)


'{}Weather.{}Ward,{}The weather at the station is sunny'.format('AAAA','BBBB','CCCC','DDDD')

#output
#'AAAA weather. The weather at BBBB Ward and CCCC Station is sunny'

Index number is set automatically --First {} = {0} --Second {} = {1} --Third {} = {2} ・ ・ ・


Example (multiple arguments, number specified ①)


'{0}Weather.{1}Ward,{2}The weather at the station is sunny'.format('AAAA','BBBB','CCCC','DDDD')

#output
#'AAAA weather. The weather at BBBB Ward and CCCC Station is sunny'

The result is the same as without a number.


Example (multiple arguments, number specified ②)


'{3}Weather.{2}Ward,{2}The weather at the station is sunny'.format('AAAA','BBBB','CCCC','DDDD')

#output
#'DDDD weather. The weather at CCCC Ward and CCCC Station is sunny'

・ In no particular order ・ The same number can be set multiple times


### (3) Set with character strings, numbers, and variables

Example (set by character string, numerical value, variable)


mountain = 'Mt. Kitadake'
altitude = '3193'

'{}so{}The highest mountain{}.. The altitude is{}m'.format('Japan',2,mountain,altitude)

#output
#'The second highest mountain in Japan is Mt. Kitadake. Altitude is 3193m'

・ Character string: Japan ・ Numerical value: 2 -Variable (character string): mountain ・ Variable (numerical value): altitude


### (4) Widen the width (width) `{:n}.format()` └ Formatting below ":" └ "n" 0 or more integers └ The unit is bytes └ The minimum width is the number of bytes of the argument

Example (width setting)


'{:2}Set gap in format'.format('A')

#output"'Set the gap in A format'」

-Argument "A": 1 byte -Width setting: 2 bytes ⇒ 2 bytes wide (1 byte gap)


Example (width setting "argument is larger")


'{:2}Set gap in format'.format('AAAAA')

#output"'Set gaps in AAAAA format'」

-Argument "AAAAA": 5 bytes -Width setting: 2 bytes ⇒ 5 bytes wide


Example (width setting "width 0")


'{:0}Set gap in format'.format('A')

#output(error)
#「ValueError: '=' alignment not allowed in string format specifier」

### (5) Specifying text alignment (align)
symbol Placement
< Left justified
^ Centered
> Right justified

** How to use ** {<n}.format() └ "<": Left justified. a line sign └ "n": width (integer greater than or equal to 0)


Example (left justified)


'{:<10}Set gap in format'.format('AAA')

#output
#「'Set gaps in AAA format'」

Example (centered)


'{:^10}Set gap in format'.format('AAA')

#output
#「'Set gaps in AAA format'」

Example (right justified)


'{:>10}Set gap in format'.format('AAA')

#output
#「'Set gaps in AAA format'」

Example (set the placement individually)


'The first one"{:<7}". The second "{:^7}". Third "{:>7}」'.format('AAA','BBB',333)

#output
# 'The first is "AAA". The second "BBB". The third "333"'

### (7) Fill in the blanks It is necessary to specify the arrangement.

Fill with zero

{0<n}.format() └ "0": Fill with 0 └ "<": Left justified. Placement specification


Fill with zero(Left justified)


'「{:0<10}Fill the gap with zero'.format('AAA')

#output
# '"AAA0000000" Fill the gap with zero'

Fill with zero(Centered)


'「{:0^10}Fill the gap with zero'.format('AAA')

#output
# '"000AAA0000" Fill the gap with zero'

If the gap is odd, there will be more behind.

Fill with zero(Right justified)


'「{:0>10}Fill the gap with zero'.format('AAA')

#output
# '"0000000 AAA" Fill the gap with zero'

#### Fill with arbitrary characters `{@・ Only one digit can be filled ・ Both half-width and full-width are acceptable ・ Error for 2 digits or more

@Fill with(Left justified)


'「{:@<10}Fill the gap'.format('AAA')

#output
# '「AAA@@@@@@@Fill the gap'

Fill with ★(Centered)


'「{:★^10}Fill the gap'.format('AAA')

#output
# '"★★★ AAA ★★★★" Fill the gap'

Fill with the number 5(Right justified)


'「{:5<10}Fill the gap with zero'.format('AAA')

#output
# '"AAA555 5555" Fill the gap with zero'

Character string of 2 digits or more (error)


'「{:★★^10}Fill the gap with zero'.format('AAA')

#Output (error)
# ValueError: Invalid format specifier

Two or more digits (error)


'「{:11<10}Fill the gap with zero'.format('AAA')

#Output (error)
# ValueError: Invalid format specifier

### (7) Set a comma in the thousands `'{:,}'.format()` └ Formatting below ":" └ "," Comma in thousands

Example (comma in thousands)


'{:,}'.format(123456789)

#output
# '123,456,789'

### (8) Display% (100 times numerical value) `'{:.n%}'.format()` └ Formatting below ":" └ ".n" Number of digits after the decimal point (default 6) └ The number is multiplied by 100

%display(Default)


'{:%}'.format(1)

#output
# '100.000000%'

%display(小数点以下非display)


'{:.0%}'.format(1)

#output
# '100%'

%display(2 digits after the decimal point)


'{:.2%}'.format(1)

#output
# '100.00%'

%display(15 digits after the decimal point)


'{:.15%}'.format(1)

#output
# '100.000000000000000%'

The default of 6 digits or more can be set.


### (9) Add a + sign to the numerical value `'{:+}'.format()` └ Formatting below ":" └ Add a plus / minus sign to "+"

The default is a minus sign only. └ Same as'{:-}'(no setting required)

Add a + sign


'The first"{:+}". The second "{:+}". Third "{:+}」'.format(-500, 300, 2.56)

#output
# 'The first"-500 ". The second "+300 ". Third "+2.56」'

### (10) Specify the number of decimal places `'{:.nf}'.format()` └ Formatting below ":" └ ".n" Number of decimal places (integer from 0) └ Default ": .nf" None is for the input value └ Rounding

Decimal point(Default)


'{}'.format(1.23)

#output
# '1.23'

Decimal point(2 digits)


'{:.2f}'.format(1.23456789)

#output
# '1.23'

Decimal point(0 digits)


'{:.0f}'.format(1.234345678)

#output
# '1'

Decimal point(12 digits)


'{:.12f}'.format(1.234345678)

#output
# '1.234345678000'

### (11) Fixed-point notation (e) `'{:.ne}'.format()` └ Formatting below ":" └ Number of ".n" decimal points └ 6 decimal places without default ".n"

Fixed point (default)


'{:e}'.format(123456789)

#output
# '1.234568e+08'

Fixed point (2 digits)


'{:.2e}'.format(123456789)

#output
# '1.23e+08'

Fixed point (no decimal point)


'{:.0e}'.format(123456789)

#output
# '1e+08'

Fixed point (argument is decimal)


'{:.0e}'.format(123.456789)

#output
# '1e+02'

### (12) Specify a variable in the argument `'{a}{b}{c},,,'.format(a='AAA',b=111,c='CCC')` └ Specify a variable in the argument └ Cannot be specified by index number └ Cannot be used with numbers or strings

Specify a variable in the argument


'{a}so{b}The highest mountain{c}。'.format(a='Japan',b=2,c='Mt. Kitadake')

#output
# 'The second highest mountain in Japan is Mt. Kitadake.'

Variables and strings are in error


'{a}so{b}The highest mountain{2}。'.format(a='Japan',b=2,Mt. Kitadake)

#output(error)
# SyntaxError: positional argument follows keyword argument

Variables and numbers are errors


'{a}so{1}The highest mountain{c}。'.format(a='Japan',2,c='Mt. Kitadake')

#output(error)
# SyntaxError: positional argument follows keyword argument

Cannot be specified by index number


'{0}so{1}The highest mountain{2}。'.format(a='Japan',b=2,c='Mt. Kitadake')

#output(error)
# IndexError: Replacement index 0 out of range for positional args tuple

NG without index number specification


'{}so{}The highest mountain{}。'.format(a='Japan',b=2,c='Mt. Kitadake')

#output(error)
# IndexError: Replacement index 0 out of range for positional args tuple

### (13) Convert date data to the specified character string The date of the datetime module can be converted to the specified format (character string).

datetime.date type


import datetime as dt
past = dt.date(2017,1,3)

"{0:%Y year%#m month%#d day}".format(past)

#output
# "{0:%Y year%#m month%#d day}".format(past)

datetime.datetime type


import datetime as dt
today = dt.datetime.now()

"{0:%Y year%m month%d day---%I time%M minutes%S seconds}".format(today)

#output
# 'March 20, 2020---02:08:39'

Extract individually(Month and second)


import datetime as dt
today = dt.datetime.now()

"{0:%#m month,%S seconds}".format(today)

#output
# 'March, 52 seconds'

Reference: [How to change the date format](https://qiita.com/yuta-38/items/337059e1eafab3582851#2-2format%E3%83%A1%E3%82%BD%E3%83%83] % E3% 83% 89% E3% 81% A7% E5% A4% 89% E6% 9B% B4% E3% 81% 99% E3% 82% 8B)


[Return to top](How to use the format method of #python)

Recommended Posts

[Python] Explains how to use the format function with an example
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] How to iterate with the range function?
Python: How to use async with
How to use FTP with Python
How to use python zip function
[Introduction to Python] How to get data with the listdir function
[python] How to use __command__, function explanation
[September 2020 version] Explains the procedure to use Gmail API with Python
How to use an external editor for Python development with Grasshopper
[Python] Make the format function simpler (What is f-string? Explain the difference from the format function with an example)
How to use the C library in Python
[Python] How to change the date format (display format)
Specify the Python executable to use with virtualenv
How to crop an image with Python + OpenCV
The easiest way to use OpenCV with python
[Algorithm x Python] How to use the list
How to use tkinter with python in pyenv
[Python] How to use hash function and tuple.
[Python] How to use the enumerate function (extract the index number and element)
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
python3: How to use bottle (2)
How to use the generator
[Python] How to use list 1
How to use the Raspberry Pi relay module Python
[Python] How to specify the download location with youtube-dl
How to use Python argparse
[Python] How to use the graph creation library Altair
Python: How to use pydub
[Python] How to use checkio
Specify MinGW as the compiler to use with Python
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
How to use the model learned in Lobe in Python
[Python] How to rewrite the table style with python-pptx [python-pptx]
[Python] How to use input ()
How to use the decorator
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)
python3: How to use bottle
How to use Python bytes
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
A story about how Windows 10 users created an environment to use OpenCV3 with Python 3.5
I tried to simulate how the infection spreads with Python
How to convert an array to a dictionary with Python [Application]
[python] How to use the library Matplotlib for drawing graphs
How to use Realsense's Python wrapper PyRealsense with Jetson Nano
How to use the __call__ method in a Python class
[Hyperledger Iroha] Notes on how to use the Python SDK
How to manipulate the DOM in an iframe with Selenium
[Python] I want to use the -h option with argparse
How to run an app built with Python + py2app built with Anaconda
I didn't know how to use the [python] for statement
Tips for Python beginners to use the Scikit-image example for themselves
How to get into the python development environment with Vagrant
[Python Kivy] How to create an exe file with pyinstaller
How to read an Excel file (.xlsx) with Pandas [Python]
How to use the optparse module
[Python] How to use Pandas Series
How to use Requests (Python Library)