str.format()函数是Python中一种格式化字符串的函数,可以用来替换、转换、格式化字符串中的内容,或者插入其他变量和值。它的使用方法是将要格式化的字符串作为参数传入str.format()函数,按照字符串中的格式符号,将变量和值插入到字符串中,最终得到一个格式化好的字符串。
str.format()函数的使用方法
str.format()函数的使用方法有以下几种:
- 使用位置参数:str.format(参数1,参数2,...),其中参数1、参数2等为要替换字符串中的变量,从左到右依次替换。
- 使用关键字参数:str.format(变量1=值1,变量2=值2,...),其中变量1、变量2等为要替换字符串中的变量,值1、值2等为要替换的值,按照变量名替换。
- 使用字典参数:str.format(**dict),其中dict为一个字典,字典中的键为要替换字符串中的变量,字典中的值为要替换的值,按照变量名替换。
- 使用对象参数:str.format(object),其中object为一个对象,对象中的属性名为要替换字符串中的变量,对象中的属性值为要替换的值,按照变量名替换。
str.format()函数的示例
下面是一些使用str.format()函数的示例:
# 使用位置参数 str1 = "My name is {0}, I'm {1} years old." print(str1.format("John", 20)) # 使用关键字参数 str2 = "My name is {name}, I'm {age} years old." print(str2.format(name="John", age=20)) # 使用字典参数 str3 = "My name is {name}, I'm {age} years old." dict1 = {"name": "John", "age": 20} print(str3.format(**dict1)) # 使用对象参数 class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 20) str4 = "My name is {name}, I'm {age} years old." print(str4.format(p1))
上面的代码运行结果如下:
My name is John, I'm 20 years old. My name is John, I'm 20 years old. My name is John, I'm 20 years old. My name is John, I'm 20 years old.
从上面的示例可以看出,str.format()函数可以用来替换、转换、格式化字符串中的内容,或者插入其他变量和值,使用起来非常方便。