<jupyter_start><jupyter_text>7.1. Fancier Output Formatting Formatted string literals<jupyter_code>year = 2016
event = 'Referendum'
f'Results of the {year} {event}'
yes_votes = 42_572_654
no_votes = 43_132_495
percentage = yes_votes / (yes_votes + no_votes)
'{:-9} YES votes {:7.2%}'.format(yes_votes, percentage)<jupyter_output><empty_output><jupyter_text>The str() function is meant to return representations of values which are fairly human-readable, while repr() is meant to generate representations which can be read by the interpreter.<jupyter_code>s = 'Hello, world.'
str(s)
repr(s)
str(1/7)
x = 10 * 3.25
y = 200 * 200
s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
print(s)
# The repr() of a string adds string quotes and backslashes:
hello = 'hello, world\n'
hellos = repr(hello)
print(hellos)
# The argument to repr() may be any Python object:
repr((x, y, ('spam', 'eggs')))<jupyter_output><empty_output><jupyter_text>7.1.1. Formatted String Literals<jupyter_code>import math
print(f'The value of pi is approximately {math.pi:.3f}.')
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
    print(f'{name:10} ==> {phone:10}')<jupyter_output>Sjoerd     ==>       4127
Jack       ==>       4098
Dcab       ==>       7678<jupyter_text>Other [modifiers](https://docs.python.org/3.7/library/string.htmlformatspec) can be used to convert the value before it is formatted. '!a' applies ascii(), '!s' applies str(), and '!r' applies repr():<jupyter_code>animals = 'eels'
print(f'My hovercraft is full of {animals}.')
print(f'My hovercraft is full of {animals!a}.')
print(f'My hovercraft is full of {animals!s}.')
print(f'My hovercraft is full of {animals!r}.')<jupyter_output>My hovercraft is full of eels.
My hovercraft is full of 'eels'.
My hovercraft is full of eels.
My hovercraft is full of 'eels'.<jupyter_text>7.1.2. The String format() Method<jupyter_code>print('We are the {} who say "{}!"'.format('knights', 'Ni'))
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
print('This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible'))
print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg'))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
      'Dcab: {0[Dcab]:d}'.format(table))
table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
for x in range(1, 11):
    print('{0:2d} {1:3d} {2:4d}'.format(x**1, x**2, x**3))
for x in range(1, 11):
    print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
    print(repr(x*x*x).rjust(4))
'12'.zfill(5)
'-3.14'.zfill(7)
'3.14159265359'.zfill(5)
import math
print('The value of pi is approximately %5.3f.' % math.pi)<jupyter_output>The value of pi is approximately 3.142.<jupyter_text>7.2. Reading and Writing Files<jupyter_code>f = open('fibo.py')
f
f.close()
with open('fibo.py') as f:
    read_data = f.read()
print(f.closed)
print(read_data)
f.read()<jupyter_output><empty_output><jupyter_text>7.2.1. Methods of File Objects<jupyter_code>f = open('fibo.py')<jupyter_output><empty_output><jupyter_text>When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory.<jupyter_code>f.read()
f.read()

f.seek(0)<jupyter_output><empty_output><jupyter_text>For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code:<jupyter_code>for line in f:
    print(line, end="")
f.close()
f = open('fibo.py', "a")
f.write('This is a test\n')
value = ('the answer', 42)
s = str(value)  # convert the tuple to string
f.write(s)
f.tell()
print(b'0123456789abcdef')
f.close()
with open('workfile', 'wb+') as f:
    print(f.write(b'0123456789abcdef'))
    print(f.seek(5))      # Go to the 6th byte in the file
    print(f.read(1))
    print(f.seek(-3, 2))  # Go to the 3rd byte before the end
    print(f.read(1))<jupyter_output>16
5
b'5'
13
b'd'<jupyter_text>In text files (those opened without a b in the mode string), only seeks relative to the beginning of the file are allowed (the exception being seeking to the very file end with seek(0, 2)) and the only valid offset values are those returned from the f.tell(), or zero. Any other offset value produces undefined behaviour.  7.2.2. Saving structured data with json<jupyter_code>import json
x = [1, 'simple', 'list']
json.dumps(x)
with open('workfile', 'w') as f:
    json.dump(x, f)
with open('workfile') as f:
    print(json.load(f))<jupyter_output>[1, 'simple', 'list']
{'fraction_non_alphanumeric': 0.16705582678836764, 'fraction_numerical': 0.04372744640203778, 'mean_word_length': 5.095730918499354, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 40, 'https://': 1, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '10', 'dir': 'jupyter-structured-clean-dedup', 'id': '452338', 'license': 'MIT', 'n_tokens_mistral': 1926, 'n_tokens_neox': 1788, 'n_words': 519, 'path': 'Tutorial/07 - Input and Output.ipynb', 'repo_name': 'FallenGameR/LearningPython', 'size': '4711'}