Home > Backend Development > Python Tutorial > Introduction to f string in python and its common usage

Introduction to f string in python and its common usage

PHPz
Release: 2023-06-27 12:34:16
forward
5990 people have browsed it

Preface

A friend saw that f'{}' appeared in the article related to the Faker library that I wrote before. He asked me what it meant?

Actually, this uses f-string as a formatting method. For this reason, we briefly list f-string and its common usage for your friends to use as a reference.

1. What is f-string?

Currently, Python f-string is the latest syntax to perform string formatting. Available since Python 3.6.

Python f-strings provide a faster, more readable, concise, and less error-prone way of formatting strings in Python. f Strings are prefixed with f and the value is evaluated using {} brackets. Specify format specifiers for type, padding, or alignment after the colon. For example: f'{price:.3f}', where price is the variable name and .3f indicates the precision (retaining three decimal places).

2. Common usage of formatting

There are three common formatting methods in Python, namely:

1. % symbol format specifier

2. format() function

3. f-string

The following is an example. The results are all "[Zhang San] is [18] years old this year", but different formats are used. Method:

name = "张三"
age = 18
# 最原始提供的字符串替换方法,使用了 % 运算符和经典字符串格式指定,如 %s %d 等
print("【%s】今年【%d】岁" % (name, age))  # 【张三】今年【18】岁
# Python 3.0 新增了 format() 函数,可以提供高级的格式化选项
print("【{}】今年【{}】岁".format(name, age))  # 【张三】今年【18】岁
# Python 3.6 f-string出现,使得格式化方法更加灵活,字符串前缀为 f,并使用 {} 评估值
print(f"【{name}】今年【{age}】岁")  # 【张三】今年【18】岁
Copy after login

3. Summary of common usages of f-string

The following are examples of some common usages of f-string

1. Receive expressions in f-string

num = 12
price = 6
# f-string 中可以接收表达式
print(f'【{num}】个苹果,每个【{price}】元,一共要花【{num * price}】元')
# 【12】个苹果,每个【6】元,一共要花【72】元
Copy after login

2. f-string can take values ​​from the dictionary

user = {"name": "Ace", "job": "teacher"}
print(f'【{user["name"]}】的工作是【{user["job"]}】')
# 【Ace】的工作是【teacher】
Copy after login

3. f-string formats multi-line data

name = "李四"
age = 28
job = "码农"
msg = (
    f'Name: {name}\n'
    f'Age: {age}\n'
    f'Job: {job}'
)  # 注意 msg 使用了 () 进行包裹
print(msg)
# Name: 李四
# Age: 28
# Job: 码农
Copy after login

4. Call functions in f-string

def my_max(x, y):
    """
    三目运算比较两个数字大小
    :param x: int x
    :param y: int y
    :return: x 和 y 中较大的数字
    """
    return x if x > y else y
a = 3
b = 4
print(f'【{a}】和【{b}】中较大的是【{my_max(a, b)}】')
# 【3】和【4】中较大的是【4】
Copy after login

5. f-string escape usage

print(f"Python 使用 {{}} 来计算f-string中的变量")
# Python 使用 {} 来计算f-string中的变量
print(f'你真的很\'厉害\'')  # 注意:单引号中想继续使用单引号,那就需要进行转义
# 你真的很'厉害'
Copy after login

6. f-string formatted floating point number

val = 11
# 通过 : 后跟 浮点数标识 ,可以实现格式化浮点数
print(f'{val:.3f}')  # 11.000
print(f'{val:.4f}')  # 11.0000
Copy after login

7. f-string formatted width

for i in range(1, 11):
    print(f'{i:02} {i * i:3} {i * i * i:4}')
# 01   1    1
# 02   4    8
# 03   9   27
# 04  16   64
# 05  25  125
# 06  36  216
# 07  49  343
# 08  64  512
# 09  81  729
# 10 100 1000
Copy after login

8. f-string aligned string

s1 = 'a'
s2 = 'ab'
s3 = 'abc'
s4 = 'abcd'
# 将输出的宽度设置为十个字符。 使用 > 符号,让输出结果右对齐。
print(f'{s1:>10}')
print(f'{s2:>10}')
print(f'{s3:>10}')
print(f'{s4:>10}')
#          a
#         ab
#        abc
#       abcd
# 实际上,只要大于最大的字符串长度,就可以实现右对齐,感兴趣可以试下小于最大字符串长度会有什么表现
Copy after login

9. f-string formatting time

import datetime
now = datetime.datetime.now()
print(f'{now:%Y-%m-%d %H:%M}')
# 2023-04-02 21:07
Copy after login

10. f-string receives object, note: the object must define __str__( ) or __repr__() function

class User:
    def __init__(self, name, job):
        self.name = name
        self.job = job
    def __repr__(self):
        return f"{self.name} is a {self.job}"
u = User('Ace', 'teacher')
print(f'{u}')
# Ace is a teacher
Copy after login

Note: Only supported by Python 3.6 or above!

Note: Only supported by Python 3.6 or above!

Note: Only supported by Python 3.6 or above!

The above is the detailed content of Introduction to f string in python and its common usage. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template