question archive CP1404/CP5632 - Practical Various examples of using Python string formatting

CP1404/CP5632 - Practical Various examples of using Python string formatting

Subject:Computer SciencePrice: Bought3

CP1404/CP5632 - Practical Various examples of using Python string formatting. (We prefer f-strings in this subject.) Want to read more about it? https://docs.python.org/3/library/string.html#formatstrings

"""

name = "Gibson L-5 CES"

year = 1922

cost = 16035.4

# The 'old' manual way to format text with string concatenation:

print("My guitar: " + name + ", first made in " + str(year))

# A better way - using str.format():

print("My guitar: {}, first made in {}".format(name, year))

print("My guitar: {0}, first made in {1}".format(name, year))

print("My {0} was first made in {1} (that's right, {1}!)".format(name, year))

# And with f-string formatting (introduced in Python 3.6)

print(f"My {name} was first made in {year} (that's right, {year}!)")

# Formatting currency (grouping with comma, 2 decimal places):

print("My {} would cost ${:,.2f}".format(name, cost))

print(f"My {name} would cost ${cost:,.2f}")

# Aligning columns by using width after the :

# This loop uses enumerate, useful when you want both the index and value numbers = [1, 19, 123, 456, -25] for i, number in enumerate(numbers, 1):    

print(f"Number {i} is {number:5}")

# TODO: Use f-string formatting to produce the output:

# 1922 Gibson L-5 CES for about $16,035!

# TODO: Using a for loop with the range function and string formatting,

# produce the following right-aligned output (DO NOT use a list):

#   0

#  50

# 100

# 150

 

 

Things to Notice

Use the string formatting 'mini language'; details come after the : See: https://docs.python.org/3/library/string.html#formatstrings

f-strings are not a complete replacement for .format(). There are some reasons to continue using .format() (such as with variable unpacking) so you should know both. Many Python programmers prefer f-strings for string formatting for readability and conciseness.

The part after the colon specifies the formatting. E.g., {:3} specifies to use a width of 3 (or more if needed) for the value.

By default, numbers are right-aligned and strings are left-aligned. You can change this with > or <
So, {:>6} would format the value to be right-aligned and take up 6 (or more if needed) spaces.

Things to do

Use f-string formatting to produce the output:
(Notice where the values go and also the float formatting / number of decimal places.)

1922 Gibson L-5 CES for about $16,035!

 

Using a for loop with the range function and string formatting (DO NOT use a list), produce the following output (right-aligned numbers)

 

  0
 50
100
150

pur-new-sol

Purchase A New Answer

Custom new solution created by our subject matter experts

GET A QUOTE

Related Questions