Python split any space

Python split string by space [With Examples]

In this Python tutorial, we will learn how to split the string by space in Python. In addition, we will explore the various ways of splitting a string by space in Python.

What is a String?

Before delving into the ways of splitting strings in Python, it’s important to understand what a string is.

In Python, a string is a sequence of characters enclosed in single quotes, double quotes, or triple quotes. They are immutable sequences, meaning that once a string is created, its content cannot be changed.

Splitting a String

Python’s built-in split() function is the most common method used to split a string. By default, this function splits a Python string into a list where each word is a list item.

Here is the syntax for the split() function:

str.split(separator, maxsplit) 
  • separator is the delimiter where the string is split. If not provided, white space is the default separator.
  • maxsplit is an optional argument that specifies how many splits to perform. If not provided or -1, it splits at all occurrences.
Читайте также:  Dbf reader in java

Let’s look at some examples:

Example#1 Splitting a U.S. Address

Let’s say we have an address string and we want to split it into components:

address = "1600 Pennsylvania Ave NW, Washington, DC 20500" address.split()

In this example, the split() function divides the Python string at each space character and returns a Python list of address components.

Python split string by space

Example#2 Splitting U.S. States from a String

Imagine you have a string of several U.S. states, and you want to split them into individual states:

states = "California Texas Florida New York Illinois" states.split() 

Here, the split() function splits the Python string at each space character and returns a list of U.S. states.

Python split string by space example

Limiting Python Splits

If you want to limit the number of splits, you can specify the maxsplit parameter:

Example#1 NFL Teams

teams = "Kansas City Chiefs San Francisco 49ers New England Patriots" teams.split(' ', 3) 

Here, the Python split() function splits the string at the first three spaces, and the rest of the string is returned as the fourth element of the list.

How to split string by space using python

Handling Multiple Python Spaces

The split() function treats consecutive spaces as a single separator:

Example#1 American Novels

 novels = "The Great Gatsby To Kill a Mockingbird" novels.split() 

In this example, regardless of the number of spaces between the words, the Python split() function treats them as a single separator.

How to split string by space using python example

Using Python Regular Expressions for Splitting

The re module’s split() function can handle more complex string splitting requirements. It allows for regular expression pattern matching.

Example#1 U.S. Landmarks

import re landmarks = "Statue of Liberty\tGrand Canyon\nMount Rushmore" re.split('\s+', landmarks) 

In this example, \s+ is a Python regular expression that matches any whitespace character (spaces, tabs, line breaks).

How to split string by space in python

Conclusion

Python provides various ways to split strings, including the built-in split() function and the re.split() function for more complex patterns. Understanding these methods is crucial for efficient string manipulation in Python. As we’ve seen, splitting a string by space is straightforward and allows for flexibility in handling different scenarios.

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Python Split String by Space

You can split a string with space as delimiter in Python using String.split() method.

In this tutorial, we will learn how to split a string by a space character, and whitespace characters in general, in Python using String.split() and re.split() methods.

Refer Python Split String to know the syntax and basic usage of String.split() method.

Examples

1. Split given string by single space

In this example, we will take a string which contains words/items/chunks separated by space character. We shall then split the string by space using String.split() method. split() method returns list of chunks.

Python Program

str = '63 41 92 81 69 70' #split string by single space chunks = str.split(' ') print(chunks)

2. Split given string by one or more adjacent spaces

In this example, we will take a string with chunks separated by one or more single space characters. Then we shall split the string using re.split() function. re.split() returns chunks in a list.

We shall use re python package in the following program. re.split(regular_expression, string) returns list of chunks split from string based on the regular_expression.

Python Program

import re str = '63 41 92 81 69 70' #split string by single space chunks = re.split(' +', str) print(chunks)

Regular Expression + represents one or more immediately occuring spaces. So, one or more single space characters is considered as a delimiter.

One ore more adjacent spaces are considered as a single delimiter because of the regular expression.

3. Split given string by any whitespace character

In this example, we shall split the string into chunks with any white space character as delimiter.

Following are the list of white space characters from ASCII Table.

ASCII Hex Code Description
09 horizontal tab
0A New line feed
0B Vertical Tab
0D Carriage Return/ Form Feed
20 Space

By default, String.split(), with no argument passed, splits the string into chunks with all the white space characters as delimiters.

Python Program

import re str = '63 41\t92\n81\r69 70' #split string by single space chunks = str.split() print(chunks)

Summary

In this tutorial of Python Examples, we learned how to split a string by space using String.split() and re.split() methods. Also, we learned how to split a string by considering all whitespace characters as delimiter.

Источник

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.

Источник

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