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

想要实现字符串居中,可以通过 var:^N 的方式。其中var是想要打印的变量,N是字符串长度。如果N小于var的长度,会打印全部字符串。

  1. >>> hello = "world"
  2. >>>f"{hello:^11}"
  3. ' world '
  4. >>>f"{hello:*^11}"
  5. '***world***'
  6. # Extra padding is added to the right
  7. >>>f"{hello:*^10}"
  8. '**world***'
  9. # N shorter than len(hello)
  10. >>>f"{hello:^2}"
  11. 'world'

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