当前位置:  首页>> 技术小册>> Python合辑3-字符串用法深度总结

  1. 字符串格式

f-string 和 str.format() 方法用于格式化字符串。两者都使用大括号 {} 占位符。例如:

  1. monday, tuesday, wednesday = "Monday", "Tuesday", "Wednesday"
  2. format_string_one = "{} {} {}".format(monday, tuesday, wednesday)
  3. print(format_string_one)
  4. format_string_two = "{2} {1} {0}".format(monday, tuesday, wednesday)
  5. print(format_string_two)
  6. format_string_three = "{one} {two} {three}".format(one=tuesday, two=wednesday, three=monday)
  7. print(format_string_three)
  8. format_string_four = f"{monday} {tuesday} {wednesday}"
  9. print(format_string_four)

Output:

  1. Monday Tuesday Wednesday
  2. Wednesday Tuesday Monday
  3. Tuesday Wednesday Monday
  4. Monday Tuesday Wednesday

f-strings 更具可读性,并且它们比 str.format() 方法实现得更快。因此,f-string 是字符串格式化的首选方法


该分类下的相关小册推荐: