Python string lines to list

Splitlines() Function in Python

Python Certification Course: Master the essentials

Splitlines() function in python generates a list of strings obtained by splitting the given string at specified line breaks.

Syntax of splitlines() in Python

Now, since the splitlines() function is a built-in function for the string data type in Python, its syntax is similar to other string methods, as shown below:

Here, we can observe that the splitlines() function accepts an optional parameter known as keepends. Let’s understand this parameter and its use in the splitlines() method.

Parameters of splitlines() in Python

As discussed earlier, the splitlines() function accepts only one optional parameter, which is described below:

Keepends

  • Type of the parameter — Boolean
  • Default value — False
  • Function — When the Keepends parameter is set to True, the line break statements are also included in the resulting list.

Now, let’s look at the return value of the splitlines() function. .

Return Value of splitlines() in Python

The splitlines() function returns a comma-separated list of lines extracted from a given string having line breaks. But what would happen if we give the splitlines() function an empty string or a string having no line breaks as the input?

Let’s try to understand and explore this by learning how exactly the splitlines() function is working under the hood.

Example of splitlines() Function in Python

Let’s look at an example to understand the functionality of the splitlines() function:

Splitlines Function Example

Here, we can notice that the splitlines() function returned a Python List that contains the sentences or lines present in the multi-line string input ( para ). .

What is splitlines() in Python?

Consider a scenario where you are given a task to find the sentence having the largest number of words from a given paragraph. For accomplishing this task, the first and foremost step is to extract all the sentences from the paragraph, i.e., we need a function to split the paragraph or multi-line string into a collection of sentences.

For this task, Python provides a special built-in function known as splitlines() that can split the multi-line string into a list of sentences, i.e., it returns a list of splitted lines.

Читайте также:  Php header status 500

To understand the working of the splitlines() function in Python, we need to understand the concept of line boundaries.

Line Boundaries are special statements that format text, perform line wrapping, or indicate potential line breaks. In python, these lines boundaries include:

Representation 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

The splitlines() function uses these line boundaries to locate the breakpoints and then splits the string into different parts that are stored into a Python List.

More Examples

Let’s look at some examples to understand how we can use the splitlines() function.

Example 1 : Use of Keepends Parameter

In this example, we will notice the effect on the result obtained from splitlines() function when the Keepends parameter is set to True.

Here, we can observe that the newline character ( \n ) is also present in the result of the splitlines() function.

Example 2 : Empty String Input

In this example, we will notice the effect on the result obtained from the splitlines() function when we provide an empty string or a string with no line breaks as the input.

Here, we can observe that if the input string is empty, the splitlines() function returns an empty list. Whereas, If there are no line-break characters (or line boundaries) present in the string, it returns a single-line list, i.e., it returns a list having the input string as its only element.

Example 3: String Input With Different Line Breaks

In this example, let’s understand the splitting process when the input string contains different line breaks.

Here, we can observe that the splitlines() function splits the string on each specified line break.

Example 4 : Practical Application of Splitlines Function

Now, let’s look at the practical application of the splitlines() function that we already discussed at the very beginning of this article, i.e., finding the sentence having the maximum number of words.

In the above example, firstly, we extract the sentences from the input para using the splitlines() function. We further split the sentences using another built-in string function called split() . The split() function returns a list of words by splitting the string at whitespace characters. Then we can calculate the number of words in the string by simply using the len() function.

Here, we can observe that sentence four has the largest number of words (equals 10 ), which was the expected result.

Conclusion

  • Splitlines() is a built-in function for strings in Python.
  • It generates a list of lines from a given string.
  • It splits a string according to the occurrence of different Line Boundaries.
  • In the case of an empty string, it returns an empty list.
  • In the absence of line breaks, it returns a unit-length list.
  • It can be used to extract sentences from a paragraph.

See Also

Some similar built-in Python functions are:

Источник

Python String splitlines() Method

Split a string into a list where each line is a list item:

Читайте также:  Settextcolor android studio kotlin

txt = «Thank you for the music\nWelcome to the jungle»

Definition and Usage

The splitlines() method splits a string into a list. The splitting is done at line breaks.

Syntax

Parameter Values

Parameter Description
keeplinebreaks Optional. Specifies if the line breaks should be included (True), or not (False). Default value is False

More Examples

Example

Split the string, but keep the line breaks:

txt = «Thank you for the music\nWelcome to the jungle»

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Python Split String – How to Split a String into a List or Array in Python

Shittu Olumide

Shittu Olumide

Python Split String – How to Split a String into a List or Array in Python

In this article, we will walk through a comprehensive guide on how to split a string in Python and convert it into a list or array.

We’ll start by introducing the string data type in Python and explaining its properties. Then we’ll discuss the various ways in which you can split a string using built-in Python methods such as split() , splitlines() , and partition() .

Overall, this article should be a useful resource for anyone looking to split a string into a list in Python, from beginners to experienced programmers.

What is a String in Python?

A string is a group of characters in Python that are encased in single quotes ( ‘ ‘ ) or double quotes ( » » ). This built-in Python data type is frequently used to represent textual data.

Since strings are immutable, they cannot be changed once they have been created. Any action that seems to modify a string actually produces a new string.

Concatenation, slicing, and formatting are just a few of the many operations that you can perform on strings in Python. You can also use strings with a number of built-in modules and functions, including re , str() , and len() .

There’s also a wide range of string operations, including split() , replace() , and strip() , that are available in Python. You can use them to manipulate strings in different ways.

Let’s now learn how to split a string into a list in Python.

How to Split a String into a List Using the split() Method

The split() method is the most common way to split a string into a list in Python. This method splits a string into substrings based on a delimiter and returns a list of these substrings.

myString = "Hello world" myList = myString.split() print(myList) 

In this example, we split the string «Hello world» into a list of two elements, «Hello» and «world» , using the split() method.

How to Split a String into a List Using the splitlines() Method

The splitlines() method is used to split a string into a list of lines, based on the newline character (\n) .

myString = "hello\nworld" myList = myString.splitlines() print(myList) 

In this example, we split the string «hello\nworld» into a list of two elements, «hello» and «world» , using the splitlines() method.

Читайте также:  Расширение php curl недоступно

How to Split a String into a List Using Regular Expressions with the re Module

The re module in Python provides a powerful way to split strings based on regular expressions.

import re myString = "hello world" myList = re.split('\s', myString) print(myList) 

In this example, we split the string «hello world» into a list of two elements, «hello» and «world» , using a regular expression that matches any whitespace character (\s) .

How to Split a String into a List Using the partition() Method

The partition() method splits a string into three parts based on a separator and returns a tuple containing these parts. The separator itself is also included in the tuple.

myString = "hello:world" myList = myString.partition(':') print(myList) 

In this example, we split the string «hello:world» into a tuple of three elements, «hello» , «:» , and «world» , using the partition() method.

Note: The most common method for splitting a string into a list or array in Python is to use the split() method. This method is available for any string object in Python and splits the string into a list of substrings based on a specified delimiter.

When to Use Each Method

So here’s an overview of these methods and when to use each one for quick reference:

  1. split() : This is the most common method for splitting a text into a list. You can use this method when you want to split the text into words or substrings based on a specific delimiter, such as a space, comma, or tab.
  2. partition() : This method splits a text into three parts based on the first occurrence of a delimiter. You can use this method when you want to split the text into two parts and keep the delimiter. For example, you might use partition() to split a URL into its protocol, domain, and path components. The partition() method returns a tuple of three strings.
  3. splitlines() : This method splits a text into a list of strings based on the newline characters ( \n ). You can use this method when you want to split a text into lines of text. For example, you might use splitlines() to split a multiline string into individual lines.
  4. Regular expressions: This is a more powerful method for splitting text into a list, as it allows you to split the text based on more complex patterns. For example, you might use regular expressions to split a text into sentences, based on the presence of punctuation marks. The re module in Python provides a range of functions for working with regular expressions.

Conclusion

These are some of the most common methods to split a string into a list or array in Python. Depending on your specific use case, one method may be more appropriate than the others.

Let’s connect on Twitter and on LinkedIn. You can also subscribe to my YouTube channel.

Источник

Оцените статью