在Python的access模块中,str函数用于将给定的对象转换为字符串形式。它的语法是:
str(object)参数object是要转换为字符串的对象,可以是数字、字符串、列表、元组等。
下面是一些示例:
num = 10str_num = str(num)print(str_num) # 输出:'10'print(type(str_num)) # 输出: <class 'str'>lst = [1, 2, 3]str_lst = str(lst)print(str_lst) # 输出:'[1, 2, 3]'print(type(str_lst)) # 输出: <class 'str'>tpl = (4, 5, 6)str_tpl = str(tpl)print(str_tpl) # 输出:'(4, 5, 6)'print(type(str_tpl)) # 输出: <class 'str'>str函数还可以用于自定义类,但需要在类中实现__str__方法,该方法返回对象的字符串表示形式。例如:
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})"person = Person("Alice", 25)str_person = str(person)print(str_person) # 输出:Person(name=Alice, age=25)print(type(str_person)) # 输出: <class 'str'>这样,通过str函数就可以将自定义类的对象转换为字符串形式。

