Split string using a newline delimiter with Python

后端 未结 5 1097
故里飘歌
故里飘歌 2020-11-27 18:01

I need to delimit the string which has new line in it. How would I achieve it? Please refer below code.

Input:

data = \"\"\"a,b,c
d,e,f
g,h,i
j,k,l\"         


        
5条回答
  •  难免孤独
    2020-11-27 18:26

    If you want to split only by newlines, you can use str.splitlines():

    Example:

    >>> data = """a,b,c
    ... d,e,f
    ... g,h,i
    ... j,k,l"""
    >>> data
    'a,b,c\nd,e,f\ng,h,i\nj,k,l'
    >>> data.splitlines()
    ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
    

    With str.split() your case also works:

    >>> data = """a,b,c
    ... d,e,f
    ... g,h,i
    ... j,k,l"""
    >>> data
    'a,b,c\nd,e,f\ng,h,i\nj,k,l'
    >>> data.split()
    ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
    

    However if you have spaces (or tabs) it will fail:

    >>> data = """
    ... a, eqw, qwe
    ... v, ewr, err
    ... """
    >>> data
    '\na, eqw, qwe\nv, ewr, err\n'
    >>> data.split()
    ['a,', 'eqw,', 'qwe', 'v,', 'ewr,', 'err']
    

提交回复
热议问题