Basic python string [closed]

2020-05-10 07:27发布

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 as findScore(‘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?

标签: python string
3条回答
地球回转人心会变
2楼-- · 2020-05-10 07:38

have a look at str.split. You can use it to split a string up into a list:

"foo bar baz".split()     #['foo','bar','baz'] (split on any whitespace)
"foo$bar$baz".split('$')  #['foo','bar','baz']

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):

s = 'foo$bar$baz'
s_new = s[s.find('bar'):]  #'bar$baz'
baz = s_new.split('$')[1]
print baz
查看更多
老娘就宠你
3楼-- · 2020-05-10 07:52

store string in a variable, say:

strs="""Justin$Calculus$90$Java$85$Python88$
Taylor$Calculus$73$Java$95$Python86$
Drew$Calculus$80$Java$75$Python94$
"""

loop over strs.split() using a for loop , i.e for line in strs.split() (using strs.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:

['Justin', 'Calculus', '90', 'Java', '85', 'Python88']

rstrip("$") will remove the rightmost $ from the line

查看更多
男人必须洒脱
4楼-- · 2020-05-10 07:53

A 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 your reader.

查看更多
登录 后发表回答