Python String splitlines() Method

24-01-23 Ahmed Obaid 1254 0

The splitlines() function splits the string based on line breaks and returns a new list of the split strings. Line breaks can be a newline (\n ), a carriage return (\r) and so on. Below is a table of line breaks that divide the string.


How to formulate it like this:

string. splitlines ([keepends])

keepends: [Optional] Sets the position of the line break and can be a boolean value (True or False). It can be a number or it can be Unicode characters, such as "\n", "r\", "r\n\" and so on.

Return value: Returns a comma-separated list of lines.


A table with the line breaks dividing the string





















































Code Description
\n Line Feed
\r Carriage Return
\r\n Carriage Return + Line Feed
\v or \x0b Line Tabulation
\f or \x0c Form Feed
\x1c File Separator
\x1d Group Separator
\x1e Record Separator
\x85 Next Line (C1 Control Code)
\u2028 Line Separator
\u2029 Paragraph Separator

In the following example we will create a string containing \r\n line break characters. After that, we will call the splitlines() function and store it in a variable that we will call list, and then create a for loop and print the stringundefined divided.

 Example:

# Created a string
string = " I learn at ahmedobaid.com \n This is awesome. \r\n is super simple."
# calling splitlines method
list = string.splitlines()
#printing the split strings
for split_string in list:
print(split_string)

 The output will be:

 I learn at ahmedobaid.com 
This is awesome.
is super simple.

 In the following example we will create a string containing \r\n line break characters. Next, we will call the splitlines() function and store it in a variable that we will call list and use the word True to include and print the separators in the string.

 Example:

# Created a string
string = " I learn at ahmedobaid.com \n This is awesome. \r\n is super simple."
# calling splitlines method
#True means that line breaks will be included
list = string.splitlines(True)
#printing the split strings
print(list)

 The output will be:

[' I learn at ahmedobaid.com \n', ' This is awesome. \r\n', ' is super simple.']

 Sources undefined external:

 Built-in functions - official Python documentation

 If you have any questions or concerns, leave them in the comments



Tags


Python python data types Python String string methods python python string splitlines method

Share page