欢迎访问宙启技术站
智能推送

使用format函数格式化字符串

发布时间:2023-06-11 12:45:03

format函数是Python中的一个内置函数,用于将一个字符串中的占位符替换为指定的变量或常量值。在Python中,字符串是不可变的,因此格式化字符串时,需要将格式化后的结果赋值给一个新的字符串变量。format函数的语法如下:

formatted_string = format(string_to_be_formatted, argument1, argument2, ...)

在这个语法中,

是需要被格式化的字符串,
等是需要被替换的变量或常量值。

在格式化字符串中,常用的占位符有以下几种:

- %d

表示整数

- %f

表示浮点数

- %s

表示字符串

- %c

表示单个字符

- %x

表示十六进制整数

- %o

表示八进制整数

- %e

表示科学计数法

使用format函数,可以将这些占位符替换为具体的数值或字符串。下面是一些示例:

# 格式化整数和浮点数
age = 30
height = 1.75
print("I am %d years old and %.2f meters tall." % (age, height))

# 格式化字符串和单个字符
name = 'Tom'
gender = 'M'
print("My name is %s and I am a %c." % (name, gender))

# 格式化十六进制整数和八进制整数
number = 123
print("The decimal number %d is %x in hexadecimal and %o in octal." % (number, number, number))

# 使用format函数格式化字符串
price = 49.9
quantity = 2
total = price * quantity
print("You bought {} items and the total cost is ${}.".format(quantity, total))

以上代码可以输出以下结果:

I am 30 years old and 1.75 meters tall.
My name is Tom and I am a M.
The decimal number 123 is 7b in hexadecimal and 173 in octal.
You bought 2 items and the total cost is $99.8.

除了使用位置参数来替换占位符之外,还可以使用关键字参数来指定要替换的变量或常量值。例如:

# 使用关键字参数来格式化字符串
print("I am {age} years old and {height:.2f} meters tall.".format(age=27, height=1.73))

以上代码可以输出以下结果:

I am 27 years old and 1.73 meters tall.

通过使用格式化字符串和format函数,我们可以快捷地将变量或常量值替换为指定的占位符,并以美观的方式输出结果。这对于编写Python程序时的输出和调试非常有用。