String: Text

03_text

Python Strings

Strings are very powerful in Python. No other language has a string quite like Python.

String Formatting

There are several ways to format a string in Python. Here are three of them:

  • The % operator, aka the printf operator.
  • The format string method.
  • The f-string syntax.
x = 42
y = 3.14159265359
z = "I like dragons!"

# % Operator - Ugly
print('x is %i, y is %.2f, z is "%s"' % (x, y, z))

# Format Method - Better
print('x is {}, y is {:.2f}, z is "{}"'.format(x, y, z))

# F-string Syntax - Pythonic
print(f'x is {x}, y is {y:.2f}, z is "{z}"')

All three format options above, represent exactly the same line of text…

x is 42, y is 3.14, z is "I like dragons!"
x is 42, y is 3.14, z is "I like dragons!"
x is 42, y is 3.14, z is "I like dragons!"

The f-string syntax is easily the most beautiful of the three, but not because it happens to be the shortest! Its beauty comes from the fact that the structure of the code matches its meaning. Generally speaking, this guide will only focus on Pythonic examples.

Official String Documentation