str.format()是Python3中的一种字符串格式化方法,它允许多次替换和值格式化。此方法使我们可以通过位置格式将字符串中的元素连接起来。
使用单个格式化程序:
格式化程序的工作原理是,将由一对大括号{}定义的一个或多个替换字段和占位符放入字符串中,然后调用str.format()。我们希望放入占位符的值,并将其作为参数传递给格式函数的字符串连接起来。
用法: { } .format(value)
参数:
(value):可以是整数,浮点数字常量,字符串,字符甚至变量。
Returntype:返回一个格式化的字符串,该字符串的值在占位符位置作为参数传递。
代码1:format()的简单演示。
# Python3 program to demonstarte
# the str.format() method
# using format option in a simple string
print ("{}, A computer science portal for geeks."
.format("GeeksforGeeks"))
# using format option for a
# value stored in a variable
str = "This article is written in {}"
print (str.format("Python"))
# formatting a string using a numeric constant
print ("Hello, I am {} years old !".format(18))
输出:
GeeksforGeeks, A computer science portal for geeks.
This article is written in Python
Hello, I am 18 years old!
使用多个格式化程序:
格式化字符串时,可以使用多对花括号。假设如果句子中需要另一个变量替换,可以通过添加第二对花括号并将第二个值传递给方法来完成。 Python将按顺序将占位符替换为值。
用法: { } { } .format(value1, value2)
参数:
(value1, value2):可以是整数,浮点数字常量,字符串,字符甚至变量。唯一的区别是,在format()方法中作为参数传递的值的数量必须等于在字符串中创建的占位符的数量。
错误和异常:
IndexError:当string有一个额外的占位符并且我们没有在format()方法中为其传递任何值时发生。 Python通常会按默认索引为占位符分配顺序,例如0、1、2、3…。访问作为参数传递的值。因此,当遇到占位符,该占位符的索引中没有任何值作为参数传递时,它将引发IndexError。
代码2:
# Python program demonstrating Index error
# Number of placeholders are four but
# there are only three values passed
# parameters in format function.
my_string = "{}, is a {} {} science portal for {}"
print (my_string.format("GeeksforGeeks", "computer", "geeks"))
输出:
Traceback (most recent