8.2 Formatting Strings
Proper text formatting makes data easier to read and understand. Here, we present many text-formatting capabilities.
8.2.1 Presentation Types
You’ve seen basic string formatting with f-strings. When you specify a placeholder for a value in an f-string, Python assumes the value should be displayed as a string unless you specify another type. In some cases, the type is required. For example, let’s format the float
value 17.489
rounded to the hundredths position:
In [1]: f'{17.489:.2f}'
Out[1]: '17.49'
Python supports precision only for floating-point and Decimal
values. Formatting is type dependent—if you try to use .2f
to format a string like 'hello'
, a ValueError
occurs. So the presentation type f
in the format specifier ...
Get Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and The Cloud now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.