Python3 使用 f-string 格式化字符串
发布时间: 更新时间: 总字数:329
阅读时间:1m
作者: 谢先斌
分享
复制网址
专栏文章
- Python 基础知识
- python中用try来处理程序异常的集中常用方法
- Python 魔法函数
- Python2.6/7 使用 format 格式化字符串
- Python3 使用 f-string 格式化字符串(当前)
- Python path 和动态添加 path 路径
- Python 开发过程中一些基础点汇总
这篇文章主要介绍了 Python 中如何使用 format 函数格式化字符串,格式化字符串有很多种方法,基于 python 3.5 推荐使用
f-string
前言
f-string
,亦称为格式化字符串常量(formatted string literals
),是Python3.6
新引入的一种字符串格式化方法。f-string
在形式上是以f
或F
修饰符引领的字符串(f'xxx'
或F'xxx'
),以大括号{}
标明被替换的字段。
使用
简单方法
> name = 'Xianbin'
> f'Hello world, I'm {name}'
'Hello world, I'm Xianbin'
表达式求值与函数调用
> f'A total number of {24 * 8 + 4}'
'A total number of 196'
> name = 'XIANBIN'
> f'I'm {name.lower()}'
'I'm xianbin'
> import math
> f'The answer is {math.pi}'
'The answer is 1.1447298858494002'
引号、大括号与反斜杠
f-string
大括号内所用的引号不能和大括号外的引号定界符冲突,可根据情况灵活切换 '
、"
和 '''
、"""
:
多行f-string
> name = 'Xianbin'
> age = 26
> f"Hello!" \
... f"I'm {name}." \
... f"I'm {age}."
"Hello!I'm Xianbin.I'm 26."
- 上一页:Linux limits.conf 详解与配置
- 下一页:梯度
专栏文章
- Python 基础知识
- python中用try来处理程序异常的集中常用方法
- Python 魔法函数
- Python2.6/7 使用 format 格式化字符串
- Python3 使用 f-string 格式化字符串(当前)
- Python path 和动态添加 path 路径
- Python 开发过程中一些基础点汇总
最近更新
最新评论
加载中...