@@ -88,7 +88,62 @@ while(i < 10):
8888 print (" {} is less than 10" .format(i))
8989 i += 1
9090```
91- ` .format() ` is a type of printing.
91+ 92+ ### String formatting
93+ There are a few ways to format a string in Python.
94+ 95+ + Using the ` % ` operator
96+ Strings can be formatted using the % operator:
97+ 98+ ``` python
99+ >> > foo = ' world'
100+ >> > ' Hello %s ' % foo
101+ ' Hello world'
102+ ```
103+ 104+ To subsitute multiple instances, wrap the right hand side in a Tuple:
105+ 106+ ``` python
107+ >> > foo = ' James'
108+ >> > bar = ' Nancy'
109+ >> > ' Hi, my name is %s and this is %s ' % (foo, bar)
110+ ' Hi, my name is James and this is Nancy'
111+ ```
112+ 113+ You can also do variable subsitutions with a dictionary:
114+ 115+ ```
116+ >>> dict = { "name": "Mike", "country": "Canada" }
117+ >>> 'I am %(name)s and I am from %(country)s' % dict
118+ 'I am Mike and I am from Canada'
119+ ```
120+ 121+ + ` .format() `
122+ 123+ Introduced in Python 3, but is available in Python 2.7+
124+ 125+ ``` python
126+ >> > ' Hello {} ' .format(' world' )
127+ ' Hello world'
128+ ```
129+ 130+ Similar to the above, subsitutions can be referred by name:
131+ 132+ ``` python
133+ >> > ' Hi {name} , your total is ${total} ' .format(name = ' Bob' , total = 5.50 )
134+ ' Hi Bob, your total is 5ドル.5'
135+ ```
136+ 137+ + f-Strings
138+ 139+ Available in Python 3.6+. Works similar to the above, but is more powerful as arbitrary Python expressions can be embedded:
140+ 141+ ``` python
142+ >> > a = 5
143+ >> > b = 10
144+ >> > f ' Five plus ten is { a + b} and not { 2 * (a + b)} . '
145+ ' Five plus ten is 15 and not 30.'
146+ ```
92147
93148## Data Structures
94149
0 commit comments