Python split words in 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:

Читайте также:  Python очень странные дела

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.

Источник

Python split words in list

Last updated: Feb 19, 2023
Reading time · 4 min

banner

# Table of Contents

# Split a String into a List of Characters in Python

Use the list() class to split a string into a list of characters, e.g. my_list = list(my_str) .

The list() class will convert the string into a list of characters.

Copied!
my_str = 'bobby' my_list = list(my_str) # 👇️ ['b', 'o', 'b', 'b', 'y'] print(my_list)

split string into list of characters

The list class takes an iterable and returns a list object.

When a string is passed to the class, it splits the string on each character and returns a list containing the characters.

# Split a String into a list of characters using a list comprehension

Copied!
my_str = 'bobby' my_list = [letter for letter in my_str] # 👇️ ['b', 'o', 'b', 'b', 'y'] print(my_list)

split string into list of characters using list comprehension

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

You can also filter letters out of the final list when using this approach.

Copied!
my_str = 'b o b b y' my_list = [letter for letter in my_str if letter.strip()] # 👇️ ['b', 'o', 'b', 'b', 'y'] print(my_list)

The string in the example has spaces.

Instead of getting list items that contain a space, we call the strip() method on each letter and see if the result is truthy.

The str.strip method returns a copy of the string with the leading and trailing whitespace removed.

If the string stores a space, it would get excluded from the final list.

# Split a String into a list of Characters using a for loop

You can also use a simple for loop to split a string into a list of characters.

Copied!
my_str = 'bobby' my_list = [] for letter in my_str: my_list.append(letter) # 👇️ ['b', 'o', 'b', 'b', 'y'] print(my_list)

split string into list of characters using for loop

We used a for loop to iterate over the string and use the append method to add each letter to the list.

The list.append() method adds an item to the end of the list.

The method returns None as it mutates the original list.

You can also conditionally add the letter to the list.

Copied!
my_str = 'bobby' my_list = [] for letter in my_str: if letter.strip() != '': my_list.append(letter) # 👇️ ['b', 'o', 'b', 'b', 'y'] print(my_list)

The string is only added to the list if it isn’t a space.

# Split a String into a List of Characters using iterable unpacking

You can also use the iterable unpacking * operator to split a string into a list of characters.

Copied!
my_str = 'bobby' my_list = [*my_str] print(my_list) # 👉️ ['b', 'o', 'b', 'b', 'y']

Notice that we wrapped the string in a list before using iterable unpacking.

The * iterable unpacking operator enables us to unpack an iterable in function calls, in comprehensions and in generator expressions.

Copied!
example = (*(1, 2), 3) # 👇️ (1, 2, 3) print(example)

# Split a String into a List of Characters using extend

You can also use the list.extend() method to split a string into a list of characters.

Copied!
my_str = 'bobby' my_list = [] my_list.extend(my_str) print(my_list) # 👉️ ['b', 'o', 'b', 'b', 'y']

The list.extend method takes an iterable and extends the list by appending all of the items from the iterable.

Copied!
my_list = ['bobby'] my_list.extend(['hadz', '.', 'com']) print(my_list) # 👉️ ['bobby', 'hadz', '.', 'com']

The list.extend method returns None as it mutates the original list.

We can directly pass a string to the list.extend() method because strings are iterable.

Each character of the string gets added as a separate element to the list.

# Split a String into a List of Characters using map()

You can also use the map() function to split a string into a list of characters.

Copied!
my_str = 'bobby' my_list = list(map(lambda char: char, my_str)) print(my_list) # 👉️ ['b', 'o', 'b', 'b', 'y']

Instead of passing the string directly to the list() class, we used the map() function to get a map object containing the characters of the string.

The map() function takes a function and an iterable as arguments and calls the function with each item of the iterable.

The lambda function we passed to map gets called with each character of the string and returns it.

The last step is to convert the map() object to a list.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

Источник

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.

Источник

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