The print() method can be used to print objects. It adds a space between its arguments and a newline at the end.
x = 1
y = 0.0000354
z = 3.0
s = "my string\n"
print(x, y)
print(z, s)
1 3.54e-05
3.0 my string
To print internal representation of objects, use the repr() method.
print(repr(x), repr(y))
print(repr(z), repr(s))
1 3.54e-05
3.0 'my string\n'
repr([1,2,3])
'[1, 2, 3]'
We can also add additional spaces using str.ljust(n) or str.rjust(n).
for x in range(1, 11):
print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4))
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
Fancier Formatting¶
In Python, the standard way to format strings is to use the str.format() method.
The method uses {}, {index}, or {keyword} to denote argument.
print('We are the {} who say "{}!"'.format('knights', 'Ni'))
We are the knights who say "Ni!"
print('{0} and {1}'.format('spam', 'eggs'))
print('{1} and {0}'.format('spam', 'eggs'))
spam and eggs
eggs and spam
print('{0}, {1}, and {1}'.format('spam', 'eggs'))
spam, eggs, and eggs
If keyword arguments are used in the str.format() method, their values are referred to by using the name of the argument.
print('This {food} is {adjective}.'.format(
food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
Positional and keyword arguments can be arbitrarily combined:
print('The story of {0}, {1}, and {other}.'.format(
'Bill', 'Manfred', other='Georg'))
The story of Bill, Manfred, and Georg.
An optional ':' and format specifier can follow the index or keyword.
import math
print('The value of PI is approximately {0:10.3e}.'.format(math.pi))
The value of PI is approximately 3.142e+00.
table = {'Sjoerd': 412.7, 'Jack': 4098, 'Dcab': 7678}
for name, phone in table.items():
print('{0:>10} ==> {1:<10.1f}'.format(name, phone))
Sjoerd ==> 412.7
Jack ==> 4098.0
Dcab ==> 7678.0
Read and Write Text Files¶
Python can also interact with files already saved on your hard drive or create a new file and write output to the new file. Both commands will require us to open and close a file. That is done as shown here:
output_file = open('hello.txt','w')
This opens the file hello.txt in write mode (that is what the 'w' means). We could also have opened in read only mode ('r') or appending mode ('a').
In write mode, the file we name (here its hello.txt) is created if it doesn't exist or it is emptied of all contents if it does exist. Everything written to this file will start at beginning and flow from there.
In append mode, the file named is created if it doesn't exist or opened if it does exist, and everything written to the file is added at the end (appended, if you will.)
In read only mode, the file is simply opened if it exists or an error is thrown if it doesn't exist.
The file we just opened doesn't exist. So python has now created the file for us. Lets write something to our file now.
output_file.write("Hello, this is a line of text. Its rather boring, but its all I have.\n")
70
After we are done, we need to close the file.
output_file.close()
Now lets open it up in read-only mode.
input_file = open('hello.txt', 'r')
Ok, let us read a single line out of our file. We do this with the readline() command.
the_line = input_file.readline()
print(the_line)
Hello, this is a line of text. Its rather boring, but its all I have.
Yay, the string we added is in our file. Can we read anymore? We didn't add anything else, but let us try.
the_second_line = input_file.readline()
print(repr(the_second_line))
''
Lets close the file that is read only right now and open it in append and add another line.
input_file.close()
the_file = open('hello.txt', 'a')
the_file.write('This is a second statement.')
the_file.write('This is the third statement.')
the_file.write(repr(2))
the_file.close()
Now lets open this file and read it line by line. We can do this quite easily using this next loop structure.
the_big_file = open('hello.txt', 'r')
for line in the_big_file:
print(line)
the_big_file.close()
Hello, this is a line of text. Its rather boring, but its all I have.
This is a second statement.This is the third statement.2
the_file.write?
Notice that all the lines we printed were put to one single line.
This is because unlike print, file.write() does not append newline automatically. We need to append newline manually.
the_file2 = open('hello.txt', 'a')
the_file2.write('\nThis is a real new line.')
the_file2.write('\nThis is another real new line.')
the_file2.close()
Now lets print each line of our new file, and also add error handling.
the_big_file = open('hello.txt', 'r')
for line in the_big_file:
print(repr(line))
the_big_file.close()
'Hello, this is a line of text. Its rather boring, but its all I have.\n'
'This is a second statement.This is the third statement.2\n'
'This is a real new line.\n'
'This is another real new line.This is a real new line.\n'
'This is another real new line.\n'
'This is a real new line.\n'
'This is another real new line.'
With Statement¶
A convenient way is to use the with statement, which closes the file automatically.
with open('hello.txt', 'r') as the_big_file:
for line in the_big_file:
print(repr(line))
'Hello, this is a line of text. Its rather boring, but its all I have.\n'
'This is a second statement.This is the third statement.2\n'
'This is a real new line.\n'
'This is another real new line.This is a real new line.\n'
'This is another real new line.\n'
'This is a real new line.\n'
'This is another real new line.'
val = int(input('Please enter a number: '))
Please enter a number: 20
val
20
'Python' 카테고리의 다른 글
| 10. NumPy tutorial (1) | 2024.03.14 |
|---|---|
| 9. Regular Expression (0) | 2024.03.14 |
| 7. Lambda Functions (0) | 2024.03.14 |
| 6. Recursion vs. Iteration (1) | 2024.03.14 |
| 5. Function (0) | 2024.03.14 |
