-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstring_formatting_examples.py
45 lines (35 loc) · 1.51 KB
/
string_formatting_examples.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""
CP1404/CP5632 - Practical
Various examples of using Python string formatting with the str.format() method
Want to read more about it? https://docs.python.org/3/library/string.html#formatstrings
"""
name = "Gibson L-5 CES"
year = 1922
cost = 16035.40
# 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))
# Formatting currency (grouping with comma, 2 decimal places):
print("My {} would cost ${:,.2f}".format(name, cost))
# Aligning columns:
numbers = [1, 19, 123, 456, -25]
for i in range(len(numbers)):
print("Number {0} is {1:>5}".format(i + 1, numbers[i]))
# Another (nicer) version of the above loop using the enumerate function
for i, number in enumerate(numbers):
print("Number {0} is {1:>5}".format(i + 1, number))
# TODO: Using a for loop with the range function and string formatting,
# produce the following output:
# 0
# 50
# 100
for i in range(0, 101, 50):
print("{:3}".format(i))
# randint activity
import random
print(random.randint(5, 20)) # line 1 : 5 and 19
print(random.randrange(3, 10, 2)) # line 2 : 3 and 9, it does not produce a 4.
print(random.uniform(2.5, 5.5)) # line 3 : 2.5 and 5.4, could see numerous digits after the decimal.