Introduced in Python 3.6, f-strings offer several benefits over the older .format()
string method.
For one, you can bring outside variables immediately into to the string rather than pass them through as keyword arguments:
In [1]:
name = 'Fred'
# Using the old .format() method:
print('His name is {var}.'.format(var=name))
# Using f-strings:
print(f'His name is {name}.')
Pass !r
to get the string representation:
In [2]:
print(f'His name is {name!r}')
Be careful not to let quotation marks in the replacement fields conflict with the quoting used in the outer string:
In [3]:
d = {'a':123,'b':456}
print(f'Address: {d['a']} Main Street')
Instead, use different styles of quotation marks:
In [4]:
d = {'a':123,'b':456}
print(f"Address: {d['a']} Main Street")
In [5]:
library = [('Author', 'Topic', 'Pages'), ('Twain', 'Rafting', 601), ('Feynman', 'Physics', 95), ('Hamilton', 'Mythology', 144)]
for book in library:
print(f'{book[0]:{10}} {book[1]:{8}} {book[2]:{7}}')
Here the first three lines align, except Pages
follows a default left-alignment while numbers are right-aligned. Also, the fourth line's page number is pushed to the right as Mythology
exceeds the minimum field width of 8
. When setting minimum field widths make sure to take the longest item into account.
To set the alignment, use the character <
for left-align, ^
for center, >
for right.
To set padding, precede the alignment character with the padding character (-
and .
are common choices).
Let's make some adjustments:
In [6]:
for book in library:
print(f'{book[0]:{10}} {book[1]:{10}} {book[2]:.>{7}}') # here .> was added
In [7]:
from datetime import datetime
today = datetime(year=2018, month=1, day=27)
print(f'{today:%B %d, %Y}')
For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings
Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available. (We will cover downloading modules later on in the course).
Python has a built-in open function that allows us to open and play with basic file types. First we will need a file though. We're going to use some IPython magic to create a text file!
In [8]:
%%writefile test.txt
Hello, this is a quick test file.
This is the second line of the file.
In [9]:
myfile = open('whoops.txt')
To avoid this error, make sure your .txt file is saved in the same location as your notebook. To check your notebook location, use pwd:
In [10]:
pwd
Out[10]:
Alternatively, to grab files from any location on your computer, simply pass in the entire file path.
For Windows you need to use double \ so python doesn't treat the second \ as an escape character, a file path is in the form:
myfile = open("C:\\Users\\YourUserName\\Home\\Folder\\myfile.txt")
For MacOS and Linux you use slashes in the opposite direction:
myfile = open("/Users/YourUserName/Folder/myfile.txt")
In [11]:
# Open the text.txt file we created earlier
my_file = open('test.txt')
In [12]:
my_file
Out[12]:
In [13]:
# We can now read the file
my_file.read()
Out[13]:
In [14]:
# But what happens if we try to read it again?
my_file.read()
Out[14]:
This happens because you can imagine the reading "cursor" is at the end of the file after having read it. So there is nothing left to read. We can reset the "cursor" like this:
In [15]:
# Seek to the start of file (index 0)
my_file.seek(0)
Out[15]:
In [16]:
# Now read again
my_file.read()
Out[16]:
In [17]:
# Readlines returns a list of the lines in the file
my_file.seek(0)
my_file.readlines()
Out[17]:
When you have finished using a file, it is always good practice to close it.
In [18]:
my_file.close()
In [19]:
# Add a second argument to the function, 'w' which stands for write.
# Passing 'w+' lets us read and write to the file
my_file = open('test.txt','w+')
In [20]:
# Write to the file
my_file.write('This is a new first line')
Out[20]:
In [21]:
# Read the file
my_file.seek(0)
my_file.read()
Out[21]:
In [22]:
my_file.close() # always do this when you're done with a file
In [23]:
my_file = open('test.txt','a+')
my_file.write('\nThis line is being appended to test.txt')
my_file.write('\nAnd another line here.')
Out[23]:
In [24]:
my_file.seek(0)
print(my_file.read())
In [25]:
my_file.close()
In [26]:
%%writefile -a test.txt
This is more text being appended to test.txt
And another line here.
Add a blank space if you want the first line to begin on its own line, as Jupyter won't recognize escape sequences like \n
In [27]:
with open('test.txt','r') as txt:
first_line = txt.readlines()[0]
print(first_line)
Note that the with ... as ...:
context manager automatically closed test.txt
after assigning the first line of text to first_line:
In [28]:
txt.read()
In [29]:
with open('test.txt','r') as txt:
for line in txt:
print(line, end='') # the end='' argument removes extra linebreaks