Python中字符串格式化有多种方式,以下是其中常用的几种:
-
使用
%
进行格式化:类似于C语言中的printf
方式。name = "Alice" age = 11 message = "Hello, %s! You are %d years old." % (name, age) print(message)
-
使用
format()
方法进行格式化:使用大括号{}
作为占位符。name = "Bob" age = 45 message = "Hello, {}! You are {} years old.".format(name, age) print(message)
-
使用f-string进行格式化(Python 3.6及以上版本支持):在字符串前加上
f
,然后使用大括号{}
包围变量名或表达式。name = "Charlie" age = 14 message = f"Hello, {name}! You are {age} years old." print(message)
-
使用
str.format_map()
方法进行格式化:将格式化参数作为字典传递。person = {'name': 'David', 'age': 11} message = "Hello, {name}! You are {age} years old.".format_map(person) print(message)
-
使用
str.format()
方法指定格式:可以指定格式化输出的样式,如小数点后保留几位等。price = 45.143333 formatted_price = "The price is {:.2f} dollars.".format(price) print(formatted_price)
以上是一些常见的字符串格式化方式,具体使用哪种方式取决于个人偏好和需求。
还有哪些常用的字符串格式化方式是本文没有提到的,还请不吝赐教,谢谢!