首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Python中的字符串格式

在Python中,字符串格式化是一种将变量插入到字符串中的方法。Python提供了多种方法来实现字符串格式化,包括使用字符串插值、f-string和str.format()方法。

  1. 字符串插值:使用百分号(%)作为占位符,在字符串中插入变量。例如:
代码语言:python
复制
name = "John"
age = 25
print("My name is %s and I am %d years old." % (name, age))
  1. f-string:在字符串前加上f或F,然后在字符串中使用花括号({})将变量括起来。例如:
代码语言:python
复制
name = "John"
age = 25
print(f"My name is {name} and I am {age} years old.")
  1. str.format()方法:使用字符串对象的format()方法,将变量插入到字符串中。例如:
代码语言:python
复制
name = "John"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

在字符串格式化中,还可以指定变量的格式,例如补零、指定小数位数等。这些选项可以在占位符后面的格式说明符中指定。例如:

代码语言:python
复制
x = 3.14159
print("The value of x is {:.2f}".format(x))

这将输出“The value of x is 3.14”。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券