String Formatting in Python:

Option #1: %-formatting

In [2]:
name = "Eric"
age = 74
"Hello, %s. You are %s." % (name, age)
Out[2]:
'Hello, Eric. You are 74.'

Option #2: str.format()

In [4]:
"Hello, {}. You are {}.".format(name, age)
Out[4]:
'Hello, Eric. You are 74.'

Option #3:  f-Strings: A New and Improved Way to Format Strings in Python

available after Python version 3.6

In [5]:
name = "Eric"
age = 74
f"Hello, {name}. You are {age}."
Out[5]:
'Hello, Eric. You are 74.'

8.2.1 Presentation Types (d,f,e,b,o,x,X,s)

It indicated what type is being formated. For examle d for integer and f for floating point

In [1]:
f'{17.489:.2f}'
Out[1]:
'17.49'
  • Can also use the e presentation type for exponential (scientific) notation.
In [6]:
f'Scientific Notation : {17000.489:e}'
Out[6]:
'Scientific Notation : 1.700049e+04'

Integers

  • There also are integer presentation types (b, o and x or X) that format integers using the binary, octal or hexadecimal number systems.
In [7]:
f'{10:d}'
Out[7]:
'10'

Characters

In [8]:
f'{65:c} {97:c}'
Out[8]:
'A a'

Strings

  • If s specified explicitly, the value to format must be a string, an expression that produces a string or a string literal.
  • If you do not specify a presentation type, non-string values are converted to strings.
In [9]:
f'{"hello":s} {7}'
Out[9]:
'hello 7'

Floating-Point and Decimal Values

  • For extremely large and small floating-point and Decimal values, Exponential (scientific) notation can be used to format the values more compactly
In [10]:
from decimal import Decimal
In [11]:
f'{Decimal("10000000000000000000000000.0"):.3f}'
Out[11]:
'10000000000000000000000000.000'
In [12]:
f'{Decimal("10000000000000000000000000.0"):.3e}'
Out[12]:
'1.000e+25'
  • The formatted value 1.000e+25 is equivalent to

1.000 x 1025

  • If you prefer a capital E for the exponent, use the E presentation type rather than e.

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.