【问题标题】:What is the meaning of row = line.rstrip("\n").split(",")row = line.rstrip("\n").split(",") 是什么意思
【发布时间】:2020-11-02 22:57:14
【问题描述】:

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

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

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

【问题讨论】:

标签: python python-3.x char cs50


【解决方案1】:

来自the docsrstrip

返回删除了尾随字符的字符串副本。

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

同样来自the docssplit

返回字符串中的单词列表,使用 sep 作为分隔符字符串。

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

示例

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

【讨论】:

    【解决方案2】:

    一路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
    

    【讨论】:

      【解决方案3】:

      这是文档所说的:

       |  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(它是一个换行)。这给了一个长线。
      然后在每个, 处剪断线。这给出了一个列表,每个项目都是初始长行的一部分。

      【讨论】:

        【解决方案4】:

        str.rstrip([chars]) 示例:

        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 确实是一行,则您的代码将起作用。 如果喜欢

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

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

        一般建议

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

        【讨论】:

          猜你喜欢
          • 2010-12-26
          • 2020-02-23
          • 2017-12-29
          • 2015-09-02
          • 2017-07-27
          • 1970-01-01
          • 2015-07-15
          • 2020-04-20
          • 1970-01-01
          相关资源
          最近更新 更多