当前位置:  首页>> 技术小册>> Python合辑5-格式化字符串

可以便捷的通过 < 或者 > 符号来调整字符串填充。

  1. >>> greetings = "hello"
  2. >>> f"She says {greetings:>10}"
  3. 'She says hello'
  4. # Pad 10 char to the right
  5. >>> f"{greetings:>10}"
  6. ' hello'
  7. >>> f"{greetings:<10}"
  8. 'hello '
  9. # You can omit the < for left padding
  10. >>> f"{greetings:10}"
  11. 'hello
  12. ![](/uploads/images/20230730/d590863bc56064e291123c76653ba57d.png)
  13. >>> a = "1"
  14. >>> b = "21"
  15. >>> c = "321"
  16. >>> d = "4321"
  17. >>> print("\n".join((f"{a:>10}", f"{b:>10}", f"{c:>10}", f"{d:>10}")))
  18. 1
  19. 21
  20. 321
  21. 4321

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