[Python] Make the format function simpler (What is f-string? Explain the difference from the format function with an example)

[Python] Make the format function simpler (What is f-string? Explain the difference from the format function with an example)

f-string is a simple way to describe the format function.

Once you remember the shape, the basic description is the same as the format function.

table of contents

  1. [What is f-string? ](What is # 1-f-string)
  2. [Differences between f-strign and format function](# 2-Differences between f-strign and format function)
  3. [Basic syntax of f-string](# 3-Basic syntax of f-string)
  4. [Example](# 4-Example)
  5. [Substitute string and number](# Substitute string and number)
  6. [Specify element placement](#Specify element placement)
  7. [Fill the gap](#Fill the gap)
  8. Format Date (#Format Date)

## 1. What is f-string? Another way to write the format function. It is easier to write than the foramt function. It has become available relatively recently.

It has been available since python3.6 (released in December 2016).

It is called a "formatted string literal" on the official page.

Click here for details (http://docs.python.org/ja/3.6/reference/lexical_analysis.html#f-strings)


## 2. Differences between f-strign and format function

-The description is simpler with f-string. -The degree of freedom is slightly higher in the format function. └ (Many patterns can be said to be complicated)

▼ Features of f-string

・ Simple code ・ All specified by variables -Describe variables and formats as a set └ Easy to understand which variable is given what format

▼ Features of format function

-You can directly specify a numerical value or a character string as the value to be assigned. ・ You can leave blank in {}. (Index number is automatically assigned) ・ Can be specified by index number


## 3. Basic syntax of f-string `f'{A}'` └ "f": Described at the beginning. Uppercase letters are OK └ "''": Write a sentence. "" "And"'''" are OK └ "{}": Describe the variable to be assigned and the format └ "A": Variable to be assigned (optional)

Same as format function except using "f"'". Pattern without formatting below ":"


** ▼ When formatting ** `f'{A:0<10}'` └ ":": Describe the format below └ "0": Character to fill the gap (optional) └ "<": Character arrangement ( right justified, ^ center justified) └ "10": width. Specified by the number of bite  

The format setting method is the same as the format function. Click here for details (https://qiita.com/yuta-38/items/9a93eea10ccc7ac2c8ad)


## 4. Example

Substitute strings and numbers

"'My name is AAA. I'm 111 cm tall. My favorite food is BBB'"

■f-string

f-string


a='AAA'
b=111
c='BBB'

f'my name is{a}is. How tall are you{b}cm. What is your favorite food{c}'

#output
# 'My name is AAA. Height is 111 cm. Favorite food is BBB'

#### ■ format function There are multiple patterns that can be specified.

** ▼ format function ① ** .format('AAA', 111, 'BBB')

format function ①


'my name is{}is. How tall are you{}cm. What is your favorite food{}'.format('AAA', 111, 'BBB')

#output
# 'My name is AAA. Height is 111 cm. Favorite food is BBB'

It is applied in {} in the order described in () of format.

An error occurs if the number of {} is greater than the number of elements specified in format.


** ▼ format function ② ** `.format(a, b, c)`

format function ②


a='AAA'
b=111
c='BBB'
'my name is{}is. How tall are you{}cm. What is your favorite food{}'.format(a, b, c)

#output
# 'My name is AAA. Height is 111 cm. Favorite food is BBB'

** ▼ format function ③ number specification ** `.format(c, b, a)`

format function ③ number specification


a='AAA'
b=111
c='BBB'

'my name is{2}is. How tall are you{1}cm. What is your favorite food{0}'.format(c, b, a)

#output
# 'My name is AAA. Height is 111 cm. Favorite food is BBB'

** ▼ format function ④ Specify by name ** `.format(height='111', favorit='BBB', name='AAA')`

format function ③ number specification


'my name is{name}is. How tall are you{height}cm. What is your favorite food{favorit}'.format(height='111', favorit='BBB', name='AAA')

#output
# 'My name is AAA. Height is 111 cm. Favorite food is BBB'

There are many patterns that can be specified by the format function, but it is delicate whether all are necessary when actually using it.

It seems that one f-string can handle it.

f-string formatting example

Formatting is the same as the format function. (Format function)

■ Element placement specification

f'{a:^n} └ Formatting after ":" └ "^" center justified ("<" left justified, ">" right justified) └ "n" integer. Indicate the gap by the number of bits --The text placement is meaningless unless a gap is specified.

Right justified


a= 'AAA'
f'my name is{a:^9}is'

#output
# 'My name is AAA'

### ■ Fill the gap

** ▼ Fill with 0 (0 padding) **

f'{a:0>n} └ Add 0 before the element placement symbol (here ">")

0 fill


a= 'AAA'
f'my name is{a:0>9}is'

#output
# 'My name is 000000 AAA'

** ▼ Fill with arbitrary characters **

f'{a:Z>n} └ Insert the character you want to fill before the element placement symbol (here, ">") └ Symbols, letters and numbers are OK └ Only one character.

Fill with arbitrary characters


a= 'AAA'
f'my name is{a:e>9}is'

#output
# 'My name is yeah yeah yeah AAA'

■ Set the date format

f'{A:% Y year% # m month% # d day}' └ “A” Variable containing date data └ Describe the date format under ":" └ "% Y" 4 digits in the Christian era └ Month without "% # m" 0 ("% -m" for Mac) └ "% # d" month without 0 ("% -d" for Mac)

For the types of specifiers (% Y,% m, etc.) [here](https://qiita.com/yuta-38/items/ba6dce967ede22e37c60#%E6%97%A5%E4%BB%98%E3% 81% AE% E6% 8C% 87% E5% AE% 9A% E5% AD% 90% E4% B8% 80% E8% A6% A7)

Date formatting


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

f'{past:%Y year%#m month%#d day}'

#output
# f'{past:%Y year%#m month%#d day}'

Since variables and formats are set like {variable: format}, it is easy to understand what format is set for what.

In the format function, visibility is reduced because it is specified by the index number.

Format the date with the format function


import datetime as dt
past = dt.date(2017,1,3)
now = dt.date(2020,1,28)
future = dt.date(2022,1,30)

"In the old days{0:%Y year%#m month%#d day}.. now{1:%Y/%#m/%#d}.. The future is{2:%y%m%d}。".format(past, now, future)

### Other You can also specify commas in the thousands, minus signs in numbers, exponential notation, and the number of decimal places in the same way as the format function.

[Click here for details](https://qiita.com/yuta-38/items/9a93eea10ccc7ac2c8ad#format%E9%96%A2%E6%95%B0%E3%81%A7%E3%81%A7%E3% 81% 8D% E3% 82% 8B% E3% 81% 93% E3% 81% A8)

Recommended Posts

[Python] Make the format function simpler (What is f-string? Explain the difference from the format function with an example)
[Python] Explains how to use the format function with an example
[Python] Explain the difference between strftime and strptime in the datetime module with an example
Let's explain the asset allocation by the Black-Litterman model (with an execution example by Python)
What is God? Make a simple chatbot with python
[Python] Make sure the received function is a user-defined function
What is the activation function?
What is the Callback function?
[Python] What is a slice? An easy-to-understand explanation of how to use it with a concrete example.
[Python] What is pip? Explain the command list and how to use it with actual examples
Consider what you can do with Python from the Qiita article
I tried to make an image similarity function with Python + OpenCV
[Python] What is a zip function?
[Python] What is a with statement?
[Python] What is @? (About the decorator)
[python] What is the sorted key?
[Python] Make the function a lambda function
What is the python underscore (_) for?
Python> What is an extended slice?
[Introduction to Python] What is the difference between a list and a tuple?
[Python] Explains how to use the range function with a concrete example
[Example of Python improvement] What is the recommended learning site for Python beginners?
[Introduction to Python] How to write a character string with the format function
[Introduction to Python] What is the method of repeating with the continue statement?
[Implementation example] Read the file line by line with Cython (Python) from the last line
Make the Python console covered with UNKO
What is "mahjong" in the Python library? ??
Scraping from an authenticated site with python
Make the library created by Eigen in C ++ available from Python with Boost.Numpy.
Do you understand the confidence intervals correctly? What is the difference from the conviction section?
[What is an algorithm? Introduction to Search Algorithm] ~ Python ~
What is the difference between `pip` and` conda`?
[Python] Make a game with Pyxel-Use an editor-
What is wheezy in the Docker Python image?
I tried Python! ] I graduated today from "What is Python! Python!"!
About the difference between "==" and "is" in python
Make OpenCV3 available from python3 installed with pyenv
Note for formatting numbers with python format function
Generate an insert statement from CSV with Python.
What are you comparing with Python is and ==?
Make JSON into CSV with Python from Splunk
What is the difference between Unix and Linux?
Investigate the cause when an error is thrown when python3.8 is not found when using lambda-uploader with python3.8
[Introduction to Python] What is the important "if __name__ =='__main__':" when dealing with modules?