Python format()函数的功能和用法

Python format()函数的功能和用法

Python format()函数的功能和用法

在Python中,format()函数是一种用于格式化字符串的方法。它允许我们在字符串中插入变量,并指定它们的格式。本文将详细介绍format()函数的功能和用法。

基本用法

format()函数的基本语法如下:

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

在上面的示例中,我们在字符串中使用了一个占位符{},然后调用format()函数并传入一个变量name,这个变量的值将被插入到占位符的位置。

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

输出为:

Hello, Alice!
Python

指定变量的位置

我们还可以通过在占位符中指定变量的位置来控制插入的顺序:

formatted_string = "Hello, {1}! My name is {0}.".format("Alice", "Bob")
print(formatted_string)
Python

输出为:

Hello, Bob! My name is Alice.
Python

格式化数字

format()函数还可以用来格式化数字。例如,我们可以指定小数点后的位数:

pi = 3.14159265359
formatted_pi = "The value of pi is {:.2f}".format(pi)
print(formatted_pi)
Python

输出为:

The value of pi is 3.14
Python

对齐文本

我们可以使用<>^来对齐文本。<表示左对齐,>表示右对齐,^表示居中对齐:

left_aligned = "{:<10}".format("left")
right_aligned = "{:>10}".format("right")
center_aligned = "{:^10}".format("center")
print(left_aligned)
print(right_aligned)
print(center_aligned)
Python

输出为:

left      
     right
    center  

## 使用关键字参数

除了按顺序传入变量外,我们还可以使用关键字参数来指定插入的值:

```python
formatted_string = "Hello, {name}! Your age is {age}.".format(name="Alice", age=30)
print(formatted_string)
Python

输出结果为:

Hello, Alice! Your age is 30.
Python

格式化字典

如果我们要格式化一个字典,可以使用以下方法:

person = {"name": "Alice", "age": 30}
formatted_string = "Hello, {name}! Your age is {age}.".format(**person)
print(formatted_string)
Python

输出结果为:

Hello, Alice! Your age is 30.
Python

格式化对象

我们还可以使用类来定义对象,并使用format()函数来格式化对象。需要在类中定义__format__()方法:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __format__(self, format_spec):
        if format_spec == "short":
            return "Name: {}, Age: {}".format(self.name, self.age)
        elif format_spec == "long":
            return "This person's name is {}, and their age is {} years old.".format(self.name, self.age)

alice = Person("Alice", 30)
print("{}".format(alice))
print("{:short}".format(alice))
print("{:long}".format(alice))
Python

输出结果为:

<__main__.Person object at 0x7fda9548d130>
Name: Alice, Age: 30
This person's name is Alice, and their age is 30 years old.
Python

总结

format()函数是一个非常灵活和强大的字符串格式化工具,可以用于插入变量、格式化数字、对齐文本、使用关键字参数、格式化字典和对象等功能。通过熟练掌握format()函数的用法,可以使我们的Python代码更加清晰和易读。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册