Python separate string into list

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.

Читайте также:  Алгоритм шифрования rsa javascript

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.

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.

Источник

Python String split() Method

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

txt = «welcome to the jungle»

Definition and Usage

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax

Parameter Values

Parameter Description
separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is «all occurrences»

More Examples

Example

Split the string, using comma, followed by a space, as a separator:

txt = «hello, my name is Peter, I am 26 years old»

Example

Use a hash character as a separator:

Example

Split the string into a list with max 2 items:

# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split(«#», 1)

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.

Источник

6 Ways To Convert String To List Python

In this article, you will learn 6 ways to convert string to list in Python.

When you think of converting a string to a list, then you may come around different cases:

convert string to list python

  • Converting a sentence to a list of words, each word is a separate element in the list.
  • Separating a string at specific places and putting it into a list.
  • Converting a string to a list of characters, each character is a separate element in the list.
  • Converting a stringified list to list a list.

Quick Solution

If you are in a hurry then here is a quick solution to convert a string to a list.

Use the split() method to convert a string to a list.

Pass a string parameter to the split() method to cut the given string at the specified places. If no argument is passed then it will split the string at the space.

Here is an example to convert a string to a list.

# convert string to list python str = "Simple Python Code" print(str.split()) # default split at space print(str.split(" "))
['Simple', 'Python', 'Code'] ['Simple', 'Python', 'Code']

1. Using split Method

The split() is a built-in string method in Python. It splits a string into a specified place and returns a list of strings.

If the string is not specified or is None , then the algorithm will split the string at the space.

This is the best way to convert string to list in Python.

Convert a string into list of words

# convert string to list of words str = "Simple Python Code" print(str.split()) print(str.split(' ')) print(str.split('Python'))
['Simple', 'Python', 'Code'] ['Simple', 'Python', 'Code'] ['Simple ', ' Code']

If you want to check the data type of the list then use the type() method.

# checking data type str = "Simple Python Code" print(type(str.split()))

2. Python string to list using loop

Loops can be a universal path to solving any repetitive task if you can find the pattern in the problem.

Here we will use for loop to convert a string to a list.

  1. Initialize an empty list to store the list of words.
  2. Initialize an empty string to store the word.
  3. Loop through each character in the string, if the character is not a space then append it to the string word . Character by character we will get the word.
  4. If the character is a space (means we found a space) then append the string word to the list.
  5. At the end of the loop, append the last word to the list.
  6. Print the list.

Converting a string to a list of words

# convert string to list using for loop lst = [] word = '' for char in str: if char != ' ': word += char else: lst.append(word) word = '' # append last word lst.append(word) print(lst)

Using similar logic, we can convert a string to a list of characters.

But this time put every character as a separate element in the list.

Converting a string to a list of characters

# convert string to list of characters str = "Simple Python Code" lst = [] for char in str: lst.append(char) print(lst)
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']

2.1. Variations Using For loop

# using range to loop String str = "Simple Python Code" lst = [] for i in range(len(str)): if str[i] != ' ': lst.append(str[i]) else: lst.append(' ') print(lst)
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']
# using list comprehension str = "Simple Python Code" lst = [char for char in str] print(lst)
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']

3. Python String To List using list() Constructor

The list() constructor returns a list by converting the given object to a list.

The constructor takes a single argument, which is the object to be converted to a list. You can pass any object to the constructor, including a string, a list, a tuple, a dictionary, a set, etc.

Here our need is for a string so we pass the string to the constructor.

# list() constructor str = "Simple Python Code" print(list(str))
['S', 'i', 'm', 'p', 'l', 'e', ' ', 'P', 'y', 't', 'h', 'o', 'n', ' ', 'C', 'o', 'd', 'e']

4. Convert Stringified list to list — Using strip() and split()

Here we want to convert a stringified list to a list. Example of stringified list is: «[‘Simple’, ‘Python’, ‘Code’]» and we want to convert it to a list type.

Our approach here is to remove square brackets from the start and end of the stringified list and then split the stringified list using the split() method.

The strip() method removes any combination of given string characters from the beginning and end of a string.

# strip() method str = "['Simple', 'Python', 'Code']" print(str.strip("[]"))

Now split this by using split() method and using ‘, ‘ as the separator.

str = "['Simple', 'Python', 'Code']" # strip it str = str.strip("[]") # split it lst = str.split(", ") print(lst) print(type(lst))

5. Using Slice Assignment

The slice assignment operator ( [:] ) is used to insert, delete, or replace a slice of a list.

When you use the slice assignment operator on the left and a string on right, the string is converted to a list and then assigned to the slice.

# slice assignment lst = [] str = "Python" lst[:] = str print(lst)

6. Convert Stringified Number List to List — Using json.loads()

Here we want to convert a stringified list of numbers into a list. An example of a stringified list of numbers is: «[1, 2, 3]» and we want to convert it to a list type.

json.loads() method converts a JSON string to a Python object. We have to import json module first to use this method.

# json.loads() method import json # stringified list of numbers str = "[1, 2, 3, 4, 5]" lst = json.loads(str) print(lst) print(type(lst))

Conclusion

In this short guide, you learned 6 different ways to convert string to list python. Most commonly used of all for this purpose is the split() method.

But as now you know 6 different ways but now you can choose to use any depending on your requirement.

Источник

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