row = line.rstrip("\n").split(",") 是什么意思

What is the meaning of row = line.rstrip("\n").split(",")

我正在研究 cs50/pset6/DNA 我想实现这个:# Strip \n from each line and convert comma separated elements into list 我想理解这行的意思:

row = line.rstrip("\n").split(",")

能否请您解释一下语法的含义以及每个部分的作用?谢谢!

row = line.rstrip("\n").split(",")

如果和下面一样,可以直接复用rstrip

返回的string
row = line.rstrip("\n") # remove newline char at the end
row = row.split(",")    # separate one string into a list of multiple ones, based on the comma

文档是这样说的:

 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.

并且:

 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |      sep
 |        The delimiter according which to split the string.
 |        None (the default value) means split according to any whitespace,
 |        and discard empty strings from the result.
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.

综上所述,该指令首先删除每个\n(它是一个换行)。那给了一条长线。
然后在每个 , 处剪线。这给出了一个列表,每个项目都是初始长行的一部分。

来自 the docs rstrip:

Return a copy of the string with trailing characters removed.

因此,在这种情况下,它将 return 字符串末尾的 "\n"

也来自the docssplit:

Return a list of the words in the string, using sep as the delimiter string.

因此,一旦您删除了 "\n",它将 return 由 "," 分隔的字符串列表。

例子

>>> s = "a,b,c,d\n"
>>> s.rstrip("\n").split(",")
['a', 'b', 'c', 'd']

str.rstrip([字符]) 的示例:

line = "line\n\n"
line.rstrip('\n')
# line is now "line"

line = "li\nne\n\n"
line.rstrip('\n')
# line is now: "line\nne"

所以它基本上删除了作为参数从字符串右侧到最后一次出现的字符。

str.split示例(sep=None,maxsplit=-1):

line = "1,2,3"
array = line.split(',')
# array is now: [1,2,3]

line = "aebec"
array = line.split('e')
# array is now: [a,b,c]

你的例子:

line = "this,is,a,line\n"
array = line.rstrip('\n').split(',')
# array is now: [this,is,a,line]

所以首先它从字符串的右侧删除换行符到换行符的最后一个顺序出现,然后它用','将字符串分成几部分并将这些部分粘贴到数组中。

针对您的问题的建议

如果一行真的是一行,您的代码将起作用。 如果喜欢

line = "a,x\nb,z,v\nc,n,j\ndy,j,k\n"

然后删除换行符使用: line.replace('\n')

一般建议

你的问题并不难。您是否阅读过文档或尝试执行 python 解释器中的给定行?如果没有请下次这样做,文档会比我更短的时间给你答案:)