30秒学会 Python 片段 · 2023年4月15日

30秒学会 Python 片段 – Split into lines

Splits a multiline string into a list of lines.

  • Use str.split() and '\n' to match line breaks and create a list.
  • str.splitlines() provides similar functionality to this snippet.

代码实现

def split_lines(s):
  return s.split('\n')

使用样例

split_lines('This\nis a\nmultiline\nstring.\n')
# ['This', 'is a', 'multiline', 'string.' , '']

翻译自:https://www.30secondsofcode.org/python/s/split-lines