-
Notifications
You must be signed in to change notification settings - Fork 1
/
string-formatting.py
94 lines (34 loc) · 1.19 KB
/
string-formatting.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# This prints out "Hello, John!"
name = "John"
print("Hello, %s!" % name)
'''
To use two or more argument specifiers, use a tuple (parentheses):
'''
# This prints out "John is 23 years old."
name = "John"
age = 23
print("%s is %d years old." % (name, age))
'''
Any object which is not a string can be formatted using the %s operator as well. The string which returns from the "repr" method of that object is formatted as the string
'''
# This prints out: A list: [1, 2, 3]
mylist = [1,2,3]
print("A list: %s" % mylist)
'''
%s - String (or any object with a string representation, like numbers)
%d - Integers
%f - Floating point numbers
%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.
%x/%X - Integers in hex representation (lowercase/uppercase)
'''
'''
You will need to write a format string which prints out the data using the following syntax: Hello John Doe. Your current balance is $53.44.
'''
data = ("John", "Doe", 53.44)
format_string = "Hello"
print(format_string % data)
'''
data = ("John", "Doe", 53.44)
format_string = "Hello %s %s. Your current balance is $%s."
print(format_string % data)
'''