基本python字符串

2024-10-06 06:43:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我们刚刚开始在我的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 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.

我假设我需要将这个字符串赋给一个变量,但是我是使用一个变量,还是每行一个变量?在

任何一个开始的想法都将非常感激。我是Python的新手,所以请容忍我。还有,$符号的意义是什么?在


Tags: oftheyoustringfunctionjavafunctionsstudent
3条回答

将字符串存储在变量中,例如:

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

使用for循环在strs.split()上循环,即for line in strs.split() (使用strs.split()将返回一个包含所有行的列表,并以空格分隔)

现在对于每一行使用line.rstrip("$").split('$'),它将为第一行返回如下内容:

^{pr2}$

rstrip("$")将从行中删除最右边的$

阅读这篇文章的一个方便方法是使用csv模块。它用于逗号分隔值,但您可以更改分隔符并使用$。在

您需要使用delimiter='$'作为reader的参数。在

看看^{}。您可以使用它将字符串拆分为一个列表:

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

从这里开始,只需将字符串拆分为适当的列表,然后在列表上进行适当的迭代以选择所需的元素。在

另外,您可以使用^{}来获取类名的索引,并在$上的拆分之前使用切片来分割字符串。这样可以更容易地获得特定分数(无需额外迭代):

^{pr2}$

相关问题 更多 >