Python格式化操作符使用

format() 是 Python 中用于字符串格式化的方法,它提供了灵活的方式来插入和格式化值到字符串中。他通过{}一对花括号来进行操作,下面是 format() 方法的用法详解:

基本用法:

formatted_string = "Hello, {}!".format(name)

在上面的例子中,{} 是占位符,它会在字符串中被 format() 方法的参数 name 替换。

按顺序插入多个值:

formatted_string = "Hello, {}! Today is {}.".format(name, date)

在这个例子中,我们使用两个占位符 {} 来插入两个值 name 和 date

指定位置插入值:

formatted_string = "Hello, {1}! Today is {0}.".format(date, name)

在上面的例子中,我们使用 {0} 和 {1} 来指定要插入的值的位置。

指定关键字插入值:

formatted_string = "Hello, {name}! Today is {date}.".format(date="2022-01-01", name="Alice")

 

在这个例子中,我们使用关键字参数来指定要插入的值,并在占位符中使用相应的关键字。

格式化数字:

formatted_number = "{:.2f}".format(3.14159)

在这个例子中,我们使用格式化字符串 "{:.2f}" 将浮点数 3.14159 格式化为保留两位小数的字符串。

对齐文本:

formatted_string = "{:<10}{}".format("Left", "Right")
符号 对齐方式
< 左对齐
> 右对齐
^ 居中

进制转换:

b 十进制
o 八进制
x/X 十六进制(字母大小写)

你可能感兴趣的:(python,开发语言)