Get the App
SLTechnology News&Howtos  ›  Development  › 

Methods of python format formatting and digital formatting

Shulou Source: shulou.com Published: 2022-06-01 11:45:28 09月24日 Update

这篇"python format格式化和数字格式化的方法"文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇"python format格式化和数字格式化的方法"文章吧。

1.format() 基本用法

python2.6 开始,新增了一种格式化字符串的函数str.format(),

它增强了字符串格式化的功能

基本语法是通过{} 和 : 来代替以前的 % .

format 函数可以接受不限个参数,位置可以不按顺序。

a = "姓名:{0},年龄:{1}"print(a.format("小明",18)) b = "姓名:{0},年龄:{1},{0}是个学生"print(b.format("小明",18)) c = "姓名:{name},年龄:{age}"print(c.format(age=19,name="小明"))

可以通过{索引}/{参数名},直接映射参数值,实现对字符串的格式化;

2.填充与对齐

填充跟对齐一起使用

^, 分别是居中,左对齐,右对齐,后面带宽度

# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充

print("{:*>8}".format("245")) print("我是{0},我喜欢语文{1:*8}".format("小明","666"))3.数字格式化

# 浮点数通过 f,整数通过 d 进行需要的格式化。

a = "{0},钱:{1:.2f}"print(a.format("小明",3333.23456))test_0="{0:.2f}"print(test_0.format(3.1415926)) test_1="{0:+.2f}"print(test_1.format(3.1415926)) test_2="{0:.0f}"print(test_2.format(3.1415926)) test_3="{0:0>2d}"print(test_3.format(5)) test_4="{0:x

Tags: Format content character Xiaoming number method parameter name string age function article knowledge article value location function can pass most of the students Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Linux MariaDB Shulou Tech Info Redmi