欢迎访问宙启技术站
智能推送

format()函数使用及示例

发布时间:2023-06-30 22:10:49

format()函数是Python中用来格式化字符串的函数。它的作用是根据指定的格式,将变量插入到字符串中。

format()函数的基本语法是:

字符串.format(变量1, 变量2, ...)

其中,字符串是需要格式化的字符串,变量1、变量2等是需要插入到字符串中的变量。

format()函数支持多种格式化方式,下面列举了一些常用的示例:

1. 简单插入变量

name = "Alice"
age = 20
print("My name is {}, and I am {} years old.".format(name, age))

输出结果:

My name is Alice, and I am 20 years old.

2. 指定变量的位置

name = "Alice"
age = 20
print("My name is {0}, and I am {1} years old.".format(name, age))

输出结果:

My name is Alice, and I am 20 years old.

3. 指定变量的名称

name = "Alice"
age = 20
print("My name is {name}, and I am {age} years old.".format(name=name, age=age))

输出结果:

My name is Alice, and I am 20 years old.

4. 格式化数字

num = 1234.56789
print("The number is {:.2f}".format(num))

输出结果:

The number is 1234.57

5. 对齐文本

text = "hello"
print("{:^10}".format(text))  # 居中对齐
print("{:>10}".format(text))  # 右对齐
print("{:<10}".format(text))  # 左对齐

输出结果:

  hello   
     hello
hello     

6. 填充字符

text = "hello"
print("{:_^10}".format(text))  # 使用下划线填充
print("{:*<10}".format(text))  # 使用星号填充
print("{:~>10}".format(text))  # 使用波浪线填充

输出结果:

__hello___
hello*****
*****hello

format()函数的参数还可以是字典、列表等,可以使用索引或键来访问对应的值。

除了format()函数,还可以使用f-string(格式化字符串字面值)来进行字符串格式化。f-string是Python 3.6及以上版本新增的功能,使用方法更加简洁清晰。例如:

name = "Alice"
age = 20
print(f"My name is {name}, and I am {age} years old.")

输出结果:

My name is Alice, and I am 20 years old.

总结:

format()函数是一种常用的字符串格式化方式,可以根据需要插入变量、对齐文本、填充字符等。它的灵活性和多样化的格式化选项能够满足各种字符串格式化的需求。但对于Python 3.6及以上版本,推荐使用更为简洁的f-string来进行字符串格式化。