Python String splitlines() Method

The Python splitlines() method is used to break a string at line boundaries, such as \n (newline), \r (carriage return), \r\n (carriage return + newline) and others. It returns a list of the split strings.

For example:

sentence = "This is a\nmulti-line\nstring."
result = sentence.splitlines()
print(result)

# Output: ['This is a', 'multi-line', 'string.']

You can also pass an optional parameter keeplinebreaks to the splitlines() method. If it is True, then the line breaks are preserved as part of the split strings.

For example:

sentence = "This is another\r\nmulti-line\r\nstring."
result = sentence.splitlines(True)
print(result)

# Output: ['This is another\r\n', 'multi-line\r\n', 'string.']

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Python float() Built in Function

Python bool() Built in Function

Python Printing Readable Results

Python exec() Built in Function