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

可以用f-string打印自定义对象。默认设置是,如果向f-string表达式传递了一个对象,它将会显示该对象 str 方法的返回值。不过,也可以用显式转换操作标志来打印repr的值。
● !r - 使用 repr() 将值转化为文本.
● !s - 使用 str() 将值转化为文本.

  1. >>> class Color:
  2. def __init__(self, r: float = 255, g: float = 255, b: float = 255):
  3. self.r = r
  4. self.g = g
  5. self.b = b
  6. def __str__(self) -> str:
  7. return "A RGB color"
  8. def __repr__(self) -> str:
  9. return f"Color(r={self.r}, g={self.g}, b={self.b})"
  10. >>> c = Color(r=123, g=32, b=255)
  11. # 如不加任何操作符, 会打印 __str__ 的值
  12. >>> f"{c}"
  13. 'A RGB color'
  14. # 用`obj!r` 的话会打印 __repr__ 的值
  15. >>> f"{c!r}"
  16. 'Color(r=123, g=32, b=255)'
  17. # 使用!s跟默认值一样
  18. >>> f"{c!s}"
  19. 'A RGB color'

Python也允许通过定义不同类型使用format方法控制格式化结果,下面的例子会展示所有可能情况。

  1. >>> class Color:
  2. def __init__(self, r: float = 255, g: float = 255, b: float = 255):
  3. self.r = r
  4. self.g = g
  5. self.b = b
  6. def __str__(self) -> str:
  7. return "A RGB color"
  8. def __repr__(self) -> str:
  9. return f"Color(r={self.r}, g={self.g}, b={self.b})"
  10. >>> c = Color(r=123, g=32, b=255)
  11. # When no option is passed, the __str__ result is printed
  12. >>> f"{c}"
  13. 'A RGB color'
  14. # When `obj!r` is used, the __repr__ output is printed
  15. >>> f"{c!r}"
  16. 'Color(r=123, g=32, b=255)'
  17. # Same as the default
  18. >>> f"{c!s}"
  19. 'A RGB color'
  20. Python also allows us to control the formatting on a per-type basis through the __format__ method. The following example shows how you can do all of that.
  21. >>> class Color:
  22. def __init__(self, r: float = 255, g: float = 255, b: float = 255):
  23. self.r = r
  24. self.g = g
  25. self.b = b
  26. def __str__(self) -> str:
  27. return "A RGB color"
  28. def __repr__(self) -> str:
  29. return f"Color(r={self.r}, g={self.g}, b={self.b})"
  30. def __format__(self, format_spec: str) -> str:
  31. if not format_spec or format_spec == "s":
  32. return str(self)
  33. if format_spec == "r":
  34. return repr(self)
  35. if format_spec == "v":
  36. return f"Color(r={self.r}, g={self.g}, b={self.b}) - A nice RGB thing."
  37. if format_spec == "vv":
  38. return (
  39. f"Color(r={self.r}, g={self.g}, b={self.b}) "
  40. f"- A more verbose nice RGB thing."
  41. )
  42. if format_spec == "vvv":
  43. return (
  44. f"Color(r={self.r}, g={self.g}, b={self.b}) "
  45. f"- A SUPER verbose nice RGB thing."
  46. )
  47. raise ValueError(
  48. f"Unknown format code '{format_spec}' " "for object of type 'Color'"
  49. )
  50. >>> c = Color(r=123, g=32, b=255)
  51. >>> f'{c:v}'
  52. 'Color(r=123, g=32, b=255) - A nice RGB thing.'
  53. >>> f'{c:vv}'
  54. 'Color(r=123, g=32, b=255) - A more verbose nice RGB thing.'
  55. >>> f'{c:vvv}'
  56. 'Color(r=123, g=32, b=255) - A SUPER verbose nice RGB thing.'
  57. >>> f'{c}'
  58. 'A RGB color'
  59. >>> f'{c:s}'
  60. 'A RGB color'
  61. >>> f'{c:r}'
  62. 'Color(r=123, g=32, b=255)'
  63. >>> f'{c:j}'
  64. ---------------------------------------------------------------------------
  65. ValueError Traceback (most recent call last)
  66. <ipython-input-20-1c0ee8dd74be> in <module>
  67. ----> 1 f'{c:j}'
  68. <ipython-input-15-985c4992e957> in __format__(self, format_spec)
  69. 29 f"- A SUPER verbose nice RGB thing."
  70. 30 )
  71. ---> 31 raise ValueError(
  72. 32 f"Unknown format code '{format_spec}' " "for object of type 'Color'"
  73. 33 )
  74. ValueError: Unknown format code 'j' for object of type 'Color'

最后,还有个用来转义ASCII字符的a操作符。更多信息可参考:
docs.python.org/3/library/functions.html#as..

  1. >>> utf_str = "Áeiöu"
  2. >>> f"{utf_str!a}"
  3. "'\\xc1ei\\xf6u'"

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