Convert Multiline into list

前端 未结 4 1171
小鲜肉
小鲜肉 2020-12-20 17:10

I have extracted a set of data from HTML page and copied to a variable. The variable looks like

names=\'\'\'
      Apple
      Ball
      Cat\'\'\'


        
相关标签:
4条回答
  • 2020-12-20 17:36

    Using splitlines() to split by newline character and strip() to remove unnecessary white spaces.

    >>> names='''
    ...       Apple
    ...       Ball
    ...       Cat'''
    >>> names
    '\n      Apple\n      Ball\n      Cat'
    >>> names_list = [y for y in (x.strip() for x in names.splitlines()) if y]
    >>> # if x.strip() is used to remove empty lines
    >>> names_list
    ['Apple', 'Ball', 'Cat']
    
    0 讨论(0)
  • 2020-12-20 17:40

    names.split('\n') should give you a list split by '\n'

    0 讨论(0)
  • 2020-12-20 17:46

    This snippet will give you a list:

    names='''Apple
    Ball
    Cat'''
    
    content = names.split("\n")
    print(content)
    

    Output:

    ['Apple', 'Ball', 'Cat']
    
    0 讨论(0)
  • 2020-12-20 17:57

    names.splitlines() should give you just that.

    0 讨论(0)
提交回复
热议问题