We just started working with string in my CSCI class, but I'm confused with a recent assignment.
You are given a long string:
"""Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$
"""
The string has three lines. It contains three students’ scores of three courses. Write a function
findScore(student, subject)
. When you call the function such asfindScore(‘Drew’,’Java’)
, the function prints“Drew got 75 of the course Java.”
In addition to the function
findScore(student, subject)
, you can write other functions. All the functions are inside one program.
I would assume that I need to assign this string to a variable, but do I use one variable, or one for each line?
Any ideas of a start would be greatly appreciated. I'm new to python so bear with me. Also, what is the significance of the $
signs?
have a look at
str.split
. You can use it to split a string up into a list:From here, it's just a matter of splitting the string into the appropriate lists, and then iterating over the lists properly to pick out the elements that you need.
Additionally, you could use
str.find
to get the index of the class name and split your string there using slicing before splitting on$
. That would make it easier to get the particular score (without an additional iteration):store string in a variable, say:
loop over
strs.split()
using a for loop , i.efor line in strs.split()
(usingstrs.split()
will return a list containing all lines, splitted at whitespace)now for each line use
line.rstrip("$").split('$')
, it'll return something like this for the first line:rstrip("$")
will remove the rightmost$
from the lineA convenient way to read this would be to use the
csv
module. It's intended for Comma Separated Values, but you can change the delimiter and use$
instead.You would need to use
delimiter='$'
as an argument to yourreader
.