Python split string into list

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»

Читайте также:  Creating header files in cpp

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.

Источник

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.

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: Split String into List with split()

Data can take many shapes and forms — and it’s oftentimes represented as strings.

Be it from a CSV file or input text, we split strings oftentimes to obtain lists of features or elements.

In this guide, we’ll take a look at how to split a string into a list in Python, with the split() method.

Split String into List in Python

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string.

By default, the delimiter is set to a whitespace — so if you omit the delimiter argument, your string will be split on each whitespace.

Let’s take a look at the behavior of the split() method:

string = "Age,University,Name,Grades" lst = string.split(',') print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) 

Our string had elements delimited with a comma, as in a CSV (comma-separated values) file, so we’ve set the delimiter appropriately.

This results in a list of elements of type str , no matter what other type they can represent:

['Age', 'University', 'Name', 'Grades'] Element types: Length: 4 

Split String into List, Trim Whitespaces and Change Capitalization

Not all input strings are clean — so you won’t always have a perfectly formatted string to split. Sometimes, strings may contain whitespaces that shouldn’t be in the «final product» or have a mismatch of capitalized and non-capitalized letters.

Thankfully, it’s pretty easy to process this list and each element in it, after you’ve split it:

# Contains whitespaces after commas, which will stay after splitting string = "age, uNiVeRsItY, naMe, gRaDeS" lst = string.split(',') print(lst) 
['age', ' uNiVeRsItY', ' naMe', ' gRaDeS'] 

No good! Each element starts with a whitespace and the elements aren’t properly capitalized at all. Applying a function to each element of a list can easily be done through a simple for loop so we’ll want to apply a strip() / trim() (to get rid of the whitespaces) and a capitalization function.

Since we’re not only looking to capitalize the first letter but also keep the rest lowercase (to enforce conformity), let’s define a helper function for that:

def capitalize_word(string): return string[:1].capitalize() + string[1:].lower() 

The method takes a string, slices it on its first letter and capitalizes it. The rest of the string is converted to lowercase and the two changed strings are then concatenated.

We can now use this method in a loop as well:

string = "age, uNiVeRsItY, naMe, gRaDeS" lst = string.split(',') lst = [s.strip() for s in lst] lst = [capitalize_word(s) for s in lst] print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) 
['Age', 'University', 'Name', 'Grades'] Element types: Length: 4 

Split String into List and Convert to Integer

What happens if you’re working with a string-represented list of integers? After splitting, you won’t be able to perform integer operations on these, since they’re ostensibly strings.

Thankfully, we can use the same for loop as before to convert the elements into integers:

string = "1,2,3,4" lst = string.split(',') lst = [int(s) for s in lst] print(lst) print('Element types:', type(lst[0])) print('Length:', len(lst)) 

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

[1, 2, 3, 4] Element types: Length: 4 

Split String into List with Limiter

Besides the delimiter, the split() method accepts a limiter — the number of times a split should occur.

It’s an integer and is defined after the delimiter:

string = "Age, University, Name, Grades" lst = string.split(',', 2) print(lst) 

Here, two splits occur, on the first and second comma, and no splits happen after that:

['Age', ' University', ' Name, Grades'] 

Conclusion

In this short guide, you’ve learned how to split a string into a list in Python.

You’ve also learned how to trim the whitespaces and fix capitalization as a simple processing step alongside splitting a string into a list.

Источник

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