ZetCode

Python str 函数

上次修改时间:2025 年 4 月 11 日

本综合指南探讨 Python 的 str 函数,该函数将对象转换为字符串表示形式。我们将介绍基本转换、自定义字符串表示形式、格式化和实践示例。

基本定义

str 函数返回对象的字符串版本。对于大多数对象,它会调用 __str__ 方法。如果不可用,它会退回到 __repr__

主要特征:创建人类可读的字符串,处理所有 Python 类型,支持自定义字符串表示形式,并在 print() 和字符串格式化中隐式使用。

基本类型转换

以下是使用不同 Python 类型的简单用法,展示了 str 如何将数字、布尔值和其他基本类型转换为字符串。

basic_str.py
# With numbers
print(str(42))        # '42'
print(str(3.14))      # '3.14'

# With booleans
print(str(True))      # 'True'
print(str(False))     # 'False'

# With None
print(str(None))      # 'None'

# With strings (no change)
print(str("hello"))   # 'hello'

此示例显示 str 将基本 Python 类型转换为其字符串表示形式。数字变为其数字字符串,布尔值变为“True”/“False”,None 变为“None”。

请注意,将字符串传递给 str 会返回相同的字符串,因为它已经是字符串。

自定义对象字符串表示

您可以通过实现 __str__ 方法来定义对象如何转换为字符串。此示例创建一个 Person 类。

custom_str.py
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def __str__(self):
        return f"Person(name='{self.name}', age={self.age})"
    
    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

p = Person("Alice", 30)
print(str(p))  # Person(name='Alice', age=30)
print(p)       # Same as above (print calls str implicitly)

Person 类实现 __str__ 以返回格式化的字符串。当我们在 Person 实例上调用 str 时,Python 会使用此方法。

__repr__ 方法提供了一个替代表示形式,当 __str__ 不可用时或在 REPL 中使用。

使用 str 进行字符串格式化

str 函数与字符串格式化配合使用以创建动态字符串。此示例显示了各种格式化技术。

formatting.py
# Old-style formatting
print("Value: %s" % str(42))          # Value: 42

# str.format()
print("Value: {}".format(str(3.14)))  # Value: 3.14

# f-strings (Python 3.6+)
value = True
print(f"Value: {str(value)}")         # Value: True

# Formatting with conversion
print(f"Value: {42!s}")               # Value: 42 (!s calls str)

这些示例演示了 str 如何与 Python 的字符串格式化系统集成。f-字符串中的 !s 转换说明符显式调用 str

格式化会自动在值上调用 str,但在某些情况下,显式转换可以使代码更清晰。

使用 str 进行文件操作

文件操作通常使用 str 在写入之前转换数据。此示例显示了使用字符串转换读取和写入文件。

files.py
# Writing different types to a file
data = [42, 3.14, True, "hello", None]

with open("data.txt", "w") as f:
    for item in data:
        f.write(str(item) + "\n")  # Convert each item to string

# Reading back
with open("data.txt", "r") as f:
    for line in f:
        print(line.strip())  # Already strings when reading

此示例通过首先将各种 Python 类型转换为字符串来将它们写入文件。文件操作需要字符串(或字节),因此对于非字符串数据,转换是必要的。

当读回时,数据已经采用字符串形式,尽管您可能需要将其解析回原始类型。

错误处理

虽然 str 几乎适用于所有 Python 对象,但了解其在边缘情况下的行为非常重要。

errors.py
class BadStr:
    def __str__(self):
        return 42  # Should return string!

try:
    print(str(BadStr()))
except TypeError as e:
    print(f"Error: {e}")  # __str__ returned non-string (type int)

# Default behavior when no __str__ is defined
class NoStr:
    pass

print(str(NoStr()))  # Uses __repr__ as fallback

这些示例演示了 str 对有问题的对象的行为。 __str__ 必须返回一个字符串,否则会引发 TypeError

当未定义 __str__ 时,Python 会退回到 __repr__,所有对象都应该具有该方法。

最佳实践

资料来源

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程