W

String Formatting

W.1 C-Style

An older way to perform string formatting in Python is with the % operator. This follows the C printf style formatting. The str.format() method (Appendix Section W.2) is preferred over the C-style formatting, and if you are using Python 3.6+ you should be using formatted string literals (f-strings) described in Section 11.4. Nonetheless, you may still find code examples that use this formatting style.

We won’t go too much into detail about this method, but here are some of the Section 11.4 examples recreated using the C printf style formatting.

For digits we can use the %d placeholder, here, the d represents an integer digit.

s = 'I only know %d digits of pi' % 7
print(s)
I only know 7 digits of pi

For strings, we can use the s placeholder. Note the string pattern uses round parentheses ( ), instead of curly braces { }. The variable passed is a Python dict, which uses { }.

print(
    "Some digits of %(cont)s: %(value).2f"
    % {"cont": "e", "value": 2.718}
)
Some digits of e: 2.72

W.2 String Formatting: .format() Method

The format string syntax1 was superseded with formatted string literals (i.e., f-strings) in Python 3.6.

1. https://docs.python.org/3/library/string.html#formatstrings

To format character strings with .format(), you essentially write a string with special placeholder characters, { }, and use the .format() method on the string to insert values into the placeholder.

var = 'flesh wound'
s = "It's just a {}!"
print(s.format(var))
It's just a flesh wound!
print(s.format('scratch'))
It's just a scratch!

The placeholders can also refer to variables multiple times.

# using variables multiple times by index
s = """Black Knight: 'Tis but a {0}.
King Arthur: A {0}? Your arm's off!
"""
print(s.format('scratch'))
Black Knight: 'Tis but a scratch.
King Arthur: A scratch? Your arm's off!

You can also give the placeholders a variable.

s = 'Hayden Planetarium Coordinates: {lat}, {lon}'
print(s.format(lat='40.7815° N', lon='73.9733° W'))
Hayden Planetarium Coordinates: 40.7815° N, 73.9733° W

W.3 Formatting Numbers

Numbers can also be formatted.

print('Some digits of pi: {}'.format(3.14159265359))
Some digits of pi: 3.14159265359

You can even format numbers and use thousands-place comma separators.

print(
  "In 2005, Lu Chao of China recited {:,} digits of pi".format(67890)
)
In 2005, Lu Chao of China recited 67,890 digits of pi

Numbers can be used to perform a calculation and formatted to a certain number of decimal values. Here we can calculate a proportion and format it into a percentage.

# the 0 in {0:.4} and {0:.4%} refer to the 0 index in this format
# the .4 refers to how many decimal values, 4
# if we provide a %, it will format the decimal as a percentage
print(
  "I remember {0:.4} or {0:.4%} of what Lu Chao recited".format(
    7 / 67890
  )
)
I remember 0.0001031 or 0.0103% of what Lu Chao recited

Finally, you can use string formatting to pad a number with zeros, similar to how zfill works on strings. When working with data, this method may be useful when working with ID numbers that were read in as numbers but should be strings.

# the first 0 refers to the index in this format
# the second 0 refers to the character to fill
# the 5 in this case refers to how many characters in total
# the d signals a digit will be used
# Pad the number with 0s so the entire string has 5 characters
print("My ID number is {0:05d}".format(42))
My ID number is 00042
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.44.92