python里面format什么意思
format()方法是Python中的一个格式化工具,用于将值插入字符串中。它接受字符串和值作为参数,并支持占位符、格式规范符和关键字参数。format()方法返回一个已格式化的字符串,支持多种格式化选项,包括对齐和浮点数格式化。
Python 中的 format() 方法
format() 方法是一种灵活强大的格式化工具,用于将值插入字符串中,创建格式良好的输出。它接受多个参数,包括要格式化的字符串以及要插入的值。
语法:
format(string, *args, **kwargs)
参数:
立即学习“Python免费学习笔记(深入)”;
用法:
format() 方法以普通字符串的形式返回一个格式化后的字符串。它支持多种格式化选项,包括:
占位符:
%s - 字符串%d - 整数%f - 浮点数
格式规范符:
{:<n} - 左对齐{:>n} - 右对齐{:^n} - 居中对齐{:.nf} - 浮点数格式化(保留 n 位小数)
关键字参数:
format(**{'name': 'John', 'age': 30})
示例:
name = "Alice"age = 25# 使用占位符print("Hello {}, you are {} years old.".format(name, age))# 使用格式规范符print("Name: {:<10} Age: {:>5}".format(name, age))# 使用关键字参数print("Name: {name} Age: {age}".format(name=name, age=age))
输出:
Hello Alice, you are 25 years old.Name: Alice Age: 25Name: Alice Age: 25