我们刚刚开始在我的CSCI类中使用string,但是我对最近的一个作业感到困惑。在
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.
我假设我需要将这个字符串赋给一个变量,但是我是使用一个变量,还是每行一个变量?在
任何一个开始的想法都将非常感激。我是Python的新手,所以请容忍我。还有,$
符号的意义是什么?在
将字符串存储在变量中,例如:
使用for循环在
strs.split()
上循环,即for line in strs.split()
(使用strs.split()
将返回一个包含所有行的列表,并以空格分隔)现在对于每一行使用
^{pr2}$line.rstrip("$").split('$')
,它将为第一行返回如下内容:rstrip("$")
将从行中删除最右边的$
阅读这篇文章的一个方便方法是使用
csv
模块。它用于逗号分隔值,但您可以更改分隔符并使用$
。在您需要使用
delimiter='$'
作为reader
的参数。在看看^{} 。您可以使用它将字符串拆分为一个列表:
从这里开始,只需将字符串拆分为适当的列表,然后在列表上进行适当的迭代以选择所需的元素。在
另外,您可以使用^{} 来获取类名的索引,并在
^{pr2}$$
上的拆分之前使用切片来分割字符串。这样可以更容易地获得特定分数(无需额外迭代):相关问题 更多 >
编程相关推荐