【问题标题】:Why should I use str.format?为什么要使用 str.format?
【发布时间】:2020-11-13 09:27:17
【问题描述】:

str.format 有什么作用?我为什么要使用它?使用有什么区别

print(a, b)

print("{} {}".format(a, b))

提前致谢。

【问题讨论】:

标签: python-3.x


【解决方案1】:

format() 方法获取传递的参数或变量,对其进行格式化,并将它们放在字符串中使用占位符符号的任何位置。

a = 5

#single formatting
b = "My name is XYZ & my age is just {}"
print (b.format(a))

#multiple formatting
c = "My name is XYZ & my age is just {}. Also I have a sibling who's age is also {}"
print(c.format(a, a))



Output:

 我的名字是 XYZ,我的年龄只有 5 岁 我的名字是 XYZ,我的年龄只有 {}。我还有一个兄弟姐妹,他的年龄也是 5 岁

【讨论】:

  • 另一种使用带有索引的#multiple 格式 c = "我的名字是 {2},我的年龄只是 {0}。我还有一个兄弟姐妹的年龄是 {1}" print(c. format(5, 8, "XYZ")) 输出:我的名字是 XYZ,我的年龄只有 5 岁。还有一个兄弟姐妹,他的年龄是 8 岁
猜你喜欢
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-16
  • 2012-08-22
  • 2016-09-12
  • 1970-01-01
相关资源
最近更新 更多