2024-08-05_simple-python-tricks-8.html


001| #:name::Simple Python Tricks #8
002| #:link::https://thehardcorecoder.com/2024/08/05/simple-python-tricks-8/
003| #:date::2024-08-05
004| #:code::
005| from sys import stdout
006| 
007| print("Hello, beautiful World!")
008| print("Hello,", "beautiful", "World!")
009| print("Hello, beautiful World!", file=stdout)
010| 
011| print("Hello, ", "beautiful ", "World!", sep='')
012| 
013| print("Hello", end='')
014| print(", ", end='')
015| print("beautiful ", end='')
016| print("World", end='')
017| print("!", end="\n\n", flush='')
018| 
019| print("Sum:", end=' ', file=stdout)
020| print(1,2,3,4,5, sep="+", end=' ', file=stdout)
021| print("=", 15, file=stdout)
022| 
023| #:code::
024| def print_sum (lines):
025|     print('Sum:', end=' ')
026|     print(*lines, sep=' + ', end=' ')
027|     print('=', sum(lines), end='\n\n')
028| 
029| print_sum([2,2])
030| print_sum([1,2,3,4,5,6,7,8,9])
031| print_sum([21,42,63,84])
032| 
033| #:code::
034| from sys import stdout
035| 
036| def print_to_file (strings, file=stdout):
037|     '''Print list of strings to a file.'''
038|     for line in strings:
039|         print(line, file=file)
040| 
041| def print_to_filename (strings, filename, encoding='utf8'):
042|     fp = open(filename, mode='w', encoding=encoding)
043|     try:
044|         print_to_file(strings, file=fp)
045|     except:
046|         raise
047|     finally:
048|         fp.close()
049|         print(f'wrote: {filename}')
050| 
051| stuff = [
052|     "Hello, beautiful World!",
053|     "",
054|     "This is a short list of strings.",
055|     "They don't say anything interesting.",
056|     "They're just here as an example.",
057|     "A real case would be more interesting!",
058|     "",
059|     "Bye for now.",
060|     ""
061| ]
062| print_to_file(stuff)
063| print_to_filename(stuff, 'stuff.text')
064| 
065| #:code::
066| stuff = [
067|     "Hello, beautiful World!",
068|     "",
069|     "This is a short list of strings.",
070|     "They don't say anything interesting.",
071|     "They're just here as an example.",
072|     "A real case would be more interesting!",
073|     "",
074|     "Bye for now.",
075|     ""
076| ]
077| lines = '\n'.join(stuff)
078| print(lines)
079| 
080| #:code::
081| stuff = ['Hello',',',' ','beautiful',' ','World','!']
082| 
083| words = ''.join(stuff)
084| print(words)
085| 
086| #:code::
087| stuff = [1, 2, 3, 4, 5, 6, 7, 8]
088| 
089| numbers = '+'.join(str(n) for n in stuff)
090| print(numbers)
091| 
092| #:code::
093| from math import pi, e
094| 
095| print('pi = %.6f' % pi)
096| print('e = %.6f' % (e,))
097| 
098| name = 'foobar'
099| ext = 'dat'
100| print('file: %s.%s' % (name, ext))
101| 
102| args = ('div', 21, 42, 0.5)
103| print('%s %d %d = %.2f' % args)
104| 
105| #:code::
106| print('|', format(42)       , '|', sep='')
107| print('|', format(42, '')   , '|', sep='')
108| print('|', format(42, '4d') , '|', sep='')
109| print('|', format(42, '04x'), '|', sep='')
110| print('|', format(42, '.1f'), '|', sep='')
111| print()
112| 
113| #:code::
114| print('|%s|' % format(42))
115| print('|%s|' % format(42, ''))
116| print('|%s|' % format(42, '4d'))
117| print('|%s|' % format(42, '04x'))
118| print('|%s|' % format(42, '.1f'))
119| print()
120| 
121| #:code::
122| print('|%d|' % 42)
123| print('|%s|' % 42)
124| print('|%4d|' % 42)
125| print('|%04x|' % 42)
126| print('|%.1f|' % 42)
127| print()
128| 
129| #:code::
130| fmt = '{0}: {1} = {2}'
131| args = [42, 'red', 3.14159]
132| 
133| print('{0}: {1} = {2}'.format(42, 'red', 3.14159))
134| print('{1}: {2} = {3}'.format(0, 42, 'red', 3.14159))
135| print(fmt.format(*args))
136| print()
137| 
138| #:code::
139| fmt = '{ix}: {name} = {value}'
140| kwargs = dict(ix=63, name='red', value=2.71828)
141| 
142| print(fmt.format(ix=63, name='red', value=2.718))
143| print(fmt.format(**kwargs))
144| print()
145| 
146| #:code::
147| fmt = '<{0},{1}> {name} = {value} ({code}-{2})'
148| args = (2.1, 4.2, 68)
149| kwargs = {'name':'red', 'value':2.718, 'code':19}
150| 
151| print(fmt.format(*args, **kwargs))
152| print()
153| 
154| #:code::
155| class xypoint:
156|     def __init__ (self, x=0.0, y=0.0):
157|         self.x = x
158|         self.y = y
159| 
160|     def __call__ (self):
161|         return (self.x, self.y)
162| 
163|     def __format__ (self, fmt):
164|         s = '[%s, %s]'
165|         t = (format(self.x,fmt), format(self.y,fmt))
166|         return s % t
167| 
168|     def __str__ (self):
169|         s = '[%.2f, %.2f]'
170|         return s % self()
171| 
172|     def __repr__ (self):
173|         s = '{"%s":{"x":%.2f, "y":%.2f}}'
174|         t = (type(self).__name__, *self())
175|         return s % t
176| 
177| pt = xypoint()
178| print(repr(pt))
179| print(str(pt))
180| print(format(pt, '.6f'))
181| print(format(pt, '.3e'))
182| print()
183| 
184| #:code::
185| from examples import xypoint
186| 
187| pt = xypoint()
188| print(f'{pt!r}')
189| print(f'{pt!s}')
190| print(f'{pt:.6f}')
191| print(f'{pt:.3e}')
192| print()
193| 
194| #:code::
195| d = 11
196| n = 640_000_000_000
197| f = 1234.5678
198| 
199| print(f'|{d}|')
200| print(f'|{d:6d}|')
201| print(f'|{d:<6d}|')
202| print(f'|{d:06d}|')
203| print(f'|{d:06x}|')
204| print()
205| 
206| print(f'|{n}|')
207| print(f'|{n:_}|')
208| print(f'|{n:,}|')
209| print(f'|{n:.2e}|')
210| print()
211| 
212| print(f'|{f}|')
213| print(f'|{f:.3f}|')
214| print(f'|{f:.2e}|')
215| print(f'|{f:+012.3f}|')
216| print(f'|{f:,.2f}|')
217| print()
218| 
219| #:code::
220| s = 'Hello!'
221| emoj = '\U0001f60e'
222| 
223| print(f'|{s:.<20}|')
224| print(f'|{s:=^20}|')
225| print(f'|{s:_>20}|')
226| print()
227| print(f'{s!s} {emoj!s}')
228| print(f'{s!r} {emoj!r}')
229| print(f'{s!a} {emoj!a}')
230| print()
231| 
232| #:code::
233| currdir = r'PIL'
234| basedir = rf'C:\users\wyrd\python\blog\{currdir}'
235| 
236| print(basedir)
237| print()
238| 
239| # Better way...
240| from os import path
241| 
242| prefix = r'C:\users\wyrd\python\blog'
243| basedir = path.join(prefix, currdir)
244| 
245| print(basedir)
246| print()
247| 
248| #:code::
249| from datetime import datetime
250| 
251| d = datetime.now()
252| fmt = '%Y-%m-%d %H:%M:%S'
253| 
254| print(f'{d!s}')
255| print(f'{d!r}')
256| print(f'{d!a}')
257| print()
258| print(f'{d:%c}')
259| print(f'{d:%A %B %d (%Y)}')
260| print(f'{d:%Y-%m-%d %H:%M:%S}')
261| print(f'{d:{fmt}}')
262| print()
263| 
264| #:code::
265| x = 2.71828
266| y = 3.14159
267| 
268| print(f'{x=}, {y=}')
269| print()
270| print(f'{x = }, {y = }')
271| print()
272| 
273| #:end:code::
274|