split()¶split() is a string method that will break a string into parts based on some delimeter
marathon_time = "4:52:20"
marathon_time_split = marathon_time.split(":")
print(marathon_time_split)
rainfall_data = "0.0, 0.4, 1.3, 1.1, 2.5, 0.0, 0.6"
rainfall_list = rainfall_data.split(", ")
print(rainfall_list)
print(float(rainfall_list[4]))
CSV files is a common, simple file format for data stored in tables. They can often be opened with either spreadsheet software or text editors.
National parks data is from https://en.wikipedia.org/wiki/List_of_areas_in_the_United_States_National_Park_System
with open("nationalparks.csv") as parkfile:
parks = parkfile.readlines()
#print(parks)
parks[3]
arches = parks[3]
print(arches)
arches = arches.rstrip()
arches_list = arches.split(',')
print(arches_list)
arches_acres = float(arches_list[3])
print(arches_list[0],"is",(arches_acres/640),"square miles")
import csv
with open("nationalparks.csv") as npfile:
parks = csv.reader(npfile)
parks = list(parks)
parks
Tabular data stored in a list-of-lists like this is sometimes called a two-dimensional list.
2D list data can be accessed with two indices, the first one for the row, and the second one for the column.
print(parks[3][0]) #row 3, column 0
print(parks[3][3]) #row 3, column 3
print(parks[3][0],"is",(float(parks[3][3])/640),"square miles")
If we want to do something with every row or every column (or both), we could iterate through it with a loop.
import csv
with open("nationalparks.csv") as npfile:
parks = csv.reader(npfile)
parks = list(parks)
park_counter = 1
while park_counter < len(parks):
print(parks[park_counter][0],"is",(float(parks[park_counter][3])/640),"square miles")
park_counter += 1
import csv
with open("nationalparks.csv") as npfile:
parks = csv.reader(npfile)
parks = list(parks)
state = input("Enter a state: ")
#let's code this up in class
import csv
with open("nationalparks.csv") as npfile:
parks = csv.reader(npfile)
parks = list(parks)
state = input("Enter a state: ")
park_counter = 1
parks_in_state = 0
while park_counter < len(parks):
if parks[park_counter][1] == state:
parks_in_state += 1
park_counter += 1
print("There are",parks_in_state,"national parks in",state)