Python | Split multiple characters from string - GeeksforGeeks (2024)

Last Updated : 01 Mar, 2024

Summarize

Comments

Improve

In Python, Strings are a basic data type that is used to store and work with textual data. Splitting a string into numerous characters is a frequent text-processing activity in Python. While coding or improvising your programming skill, you surely must have come across many scenarios where you wished to use split() in Python not to split on only one character but multiple Delimiters at once. In this article, we will see different approaches to Python string split multiple delimiters.

Input: "GeeksForGeeks, is an-awesome! website"
Output: ['GeeksForGeeks, ', 'is', 'an-awesome!', 'website']
Explanation: In This, we are splitting the multiple delimiters from the string.

In Python, We can use different approaches to split multiple Delimiters from the string. With these methods, splitting and manipulating individual characters from a string in Python is simple.

  • Using Split Function
  • Using replace()
  • Using re.split()
  • Using re.findall()

Split String By Multiple Delimiters using Split Function

In Python, we can split multiple characters from a string using split(). Here, we iterate through each delimiter and split the string using the split() function. After splitting, we join the resulting list with spaces using the join() function and we split the modified string based on whitespace to obtain the desired list of strings.

Python3

string = "GeeksForGeeks, | is an-awesome! website"

delimiters = [",", "|", ";", "!"]

for delimiter in delimiters:

string = " ".join(string.split(delimiter))

result = string.split()

print(result)

Output

['GeeksForGeeks', 'is', 'an-awesome', 'website']

Python Split By Multiple Characters using replace()

In Python, we can split multiple characters from a string using replace(). This is a very rookie way of doing the split. It does not make use of regex and is inefficient but still worth a try. If you know the characters you want to split upon, just replace them with a space and then use split().

Python3

data = "Let's_try, this now"

# printing original string

print("The original string is : " + data)

# Using replace() and split()

# Splitting characters in String

res = data.replace('_', ' ').replace(', ', ' ').split()

print("The list after performing split functionality : " + str(res))

Output

The original string is : Let's_try, this now
The list after performing split functionality : ["Let's", 'try', 'this', 'now']

Python Split By Multiple Characters using Re.split()

In Python, we can split multiple characters from a string using resplit(). This is the most efficient and commonly used method to split multiple characters at once. It makes use of regex(regular expressions) in order to do this.

Python3

import re

data = "GeeksforGeeks, is_an-awesome ! website"

print("The original string is : " + data)

# Using re.split()

# Splitting characters in String

res = re.split(', |_|-|!', data)

print("The list after performing split functionality : " + str(res))

Output

The original string is : GeeksforGeeks, is_an-awesome ! website
The list after performing split functionality : ['GeeksforGeeks', 'is', 'an', 'awesome ', ' website']

The line re.split(‘, |_|-|!’, data) tells Python to split the variable data on the characters: , or _ or or !. The symbol “|” represents or. There are some symbols in regex which are treated as special symbols and have different functions. If you wish to split on such a symbol, you need to escape it using a “\“(back-slash) and it needs one space before and after special characters.

List of special characters that need to be escaped before using them:

. \ + * ? [ ^ ] $ ( ) { } = | : 

Example: In this code, we are using resplit () to split characters from strings in Python.

Python3

import re

newData1 = "GeeksforGeeks, is_an-awesome ! app + too"

# To split "+" with one espace before and after "+" symbol and use backslash

print(re.split(', |_|-|!|\+', newData1))

newData2 = "GeeksforGeeks, is_an-awesome ! app+too"

# To split "+" without one espace before and after "+" symbol and use backslash

print(re.split(', |_|-|!|\+', newData2))

Output

['GeeksforGeeks', ' is', 'an', 'awesome', ' app', 'too']

Note: To know more about regex click here.

Split String By Multiple Delimiters using re.findall()

In Python, we can split multiple characters from a string using refindall(). This is a bit more arcane form but saves time. It also makes use of regex like above but instead of .split() method, it uses a method called .findall(). This method finds all the matching instances and returns each of them in a list. This way of splitting is best used when you don’t know the exact characters you want to split upon.

Python3

import re

data = "This, is - another : example?!"

print("The original string is : " + data)

# Using re.findall()

# Splitting characters in String

res = re.findall(r"[\w']+", data)

print("The list after performing split functionality : " + str(res))

Output

The original string is : This, is - another : example?!
The list after performing split functionality : ['This', 'is', 'another', 'example']

Here the keyword [\w’]+ indicates that it will find all the instances of alphabets or underscore(_) one or more and return them in a list. Note: [\w’]+ won’t split upon an underscore(_) as it searches for alphabets as well as underscores.

Example: In this code, we are using refindall () to split characters from strings in Python.

Python3

import re

testData = "This, is - underscored _ example?!"

print(re.findall(r"[\w']+", testData))

Output

['This', 'is', 'underscored', '_', 'example']

Character Classes

Regex cheat sheet on character description

Shorthand character classRepresents
\dAny numeric digit from 0 to 9
\DAny character that is not a numeric digit from 0 to 9
\wAny letter, numeric digit, or the underscore character
\WAny character that is not a letter, numeric digit, or the underscore character
\sAny space, tab, or newline character
\SAny character that is not a space, tab, or newline


A

agarwalkeshav8399

Python | Split multiple characters from string - GeeksforGeeks (1)

Improve

Next Article

Remove Special Characters from String Python

Please Login to comment...

Python | Split multiple characters from string - GeeksforGeeks (2024)

FAQs

Python | Split multiple characters from string - GeeksforGeeks? ›

Python Split By Multiple Characters using Re.

How do you check if a string contains several characters in Python? ›

three ways :
  1. Use the 'in' operator : 'orld' in 'Hello World' for example.
  2. Use the find() method : 'Hello World'. find('or') - this returns the index of the sub-string in the main string - returns -1 when the sub-string isn't in the main string.
  3. Use the count() method 'Hello World'.
Aug 6, 2022

How do you check how many characters a string has in Python? ›

To get the length of a string, use the len() function.

How to split two words in Python? ›

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. In this example, we split the string "Hello world" into a list of two elements, "Hello" and "world" , using the split() method.

How do you strip multiple characters from a string in Python? ›

3 Methods to Trim a String in Python
  1. strip() : Removes leading and trailing characters (whitespace by default).
  2. lstrip() : Removes leading characters (whitespace by default) from the left side of the string.
  3. rstrip() : Removes trailing characters (whitespace by default) from the right side of the string.

How to split a string every 4 characters in Python? ›

Using Wrap Function

Python comes with a built-in textwrap library that provides a wrap() function. It takes two arguments - string to be split and the number of characters to be present in each substring.

How do you check for multiple substrings in a string in Python? ›

Checking for Multiple Substrings

Here's an example: Code: string = "Hello, World!" substrings = ["Hello", "Python"] if all(substring in string for substring in substrings): print("All substrings found!") else: print("One or more substrings not found.")

How do I find two characters in a string in Python? ›

7 Answers. It is as simple as string[:2] . A function can be easily written to do it, if you need.

How do you check if a string contains all characters in Python? ›

The "in" operator of Python, which serves as a tool for comparison operations, is the quickest and easiest way to determine if a Python string includes a character. Checking whether a string includes a substring also benefits from the use of other Python functions like find(), index(), count(), and others.

How to count multiple specific letters in a string in Python? ›

To count specific characters in a string in Python, we use the string count() function. We specify the character as a substring parameter in the count() function. Also, we need to keep In mind that Python string count() accepts only a single substring parameter.

How do you find specific characters in a string in Python? ›

You can find the first occurrence of a given character in a string in Python by using the `str. index()` method. This method returns the index of the first occurrence of the specified character. If the character is not found, it raises a `ValueError`.

How do you count the number of characters in a string? ›

Python
  1. string = "The best of both worlds";
  2. count = 0;
  3. #Counts each character except space.
  4. for i in range(0, len(string)):
  5. if(string[i] != ' '):
  6. count = count + 1;
  7. #Displays the total number of characters present in the given string.
  8. print("Total number of characters in a string: " + str(count));

How to slice multiple characters in Python? ›

In Python, we can split multiple characters from a string using replace(). This is a very rookie way of doing the split. It does not make use of regex and is inefficient but still worth a try. If you know the characters you want to split upon, just replace them with a space and then use split().

How to split string with multiple special characters in Python? ›

Splitting the String Based on Multiple Delimiters:

Multiple delimiters can be specified as a parameter to the split() function by separating each delimiter with a |. The given string or line with multiple delimiters is separated using a split function called re. split() function.

What does strip() do in Python? ›

Python strip() function is used to remove extra whitespaces and specified characters from the start and from the end of the strip irrespective of how the parameter is passed. The strip() function also accepts an argument that specifies the list of characters to be removed from the original string.

How do you split a string into multiple parts in Python? ›

The string manipulation function in Python used to break down a bigger string into several smaller strings is called the split() function in Python. The split() function returns the strings as a list.

How do you split a string over multiple lines in Python? ›

splitlines() is a built-in string method in Python that is used to split a multi-line string into a list of lines. It recognizes different newline characters such as \n , \r , or \r\n and splits the string at those points.

How do I split a string between two characters? ›

Step-by-step Implementation

Take the startChar and endChar as characters after that find the index of the characters with the indexOf() method. Give the startIndex and endIndex, the parameters of the substring method then it finds the substring of the specific between of two characters. Print the substring.

How to split a string between two characters in Python? ›

If you want to extract a string between two strings such as XYZ and ABC from input string, you can use the split() function. In the above code, we first split the input string using XYZ as the delimiter. This returns a list containing two parts (before and after XYZ ).

Top Articles
Ratio & proportion - Oxford Owl for Home
How To Build a Stock Trading App: All Questions Answered
Ffxiv Palm Chippings
Gamevault Agent
News - Rachel Stevens at RachelStevens.com
Valley Fair Tickets Costco
Davante Adams Wikipedia
Hotels Near 500 W Sunshine St Springfield Mo 65807
Mohawkind Docagent
Emmalangevin Fanhouse Leak
123 Movies Black Adam
Mndot Road Closures
Erskine Plus Portal
Craigslist Heavy Equipment Knoxville Tennessee
Slag bij Plataeae tussen de Grieken en de Perzen
Oscar Nominated Brings Winning Profile to the Kentucky Turf Cup
Superhot Unblocked Games
My.doculivery.com/Crowncork
Love In The Air Ep 9 Eng Sub Dailymotion
7543460065
Committees Of Correspondence | Encyclopedia.com
Vanessawest.tripod.com Bundy
My Homework Lesson 11 Volume Of Composite Figures Answer Key
Huntersville Town Billboards
Mychart Anmed Health Login
Timeforce Choctaw
Ford F-350 Models Trim Levels and Packages
Sofia the baddie dog
City Of Durham Recycling Schedule
Sandals Travel Agent Login
Orange Park Dog Racing Results
DIY Building Plans for a Picnic Table
Otis Offender Michigan
Have you seen this child? Caroline Victoria Teague
Nicole Wallace Mother Of Pearl Necklace
The Pretty Kitty Tanglewood
Steven Batash Md Pc Photos
Tamil Play.com
Atlantic Broadband Email Login Pronto
Spinning Gold Showtimes Near Emagine Birch Run
Asian Grocery Williamsburg Va
Directions To 401 East Chestnut Street Louisville Kentucky
Academic important dates - University of Victoria
Gpa Calculator Georgia Tech
T&Cs | Hollywood Bowl
Immobiliare di Felice| Appartamento | Appartamento in vendita Porto San
Sdn Fertitta 2024
St Vrain Schoology
Online College Scholarships | Strayer University
Unpleasant Realities Nyt
Tyrone Unblocked Games Bitlife
How To Connect To Rutgers Wifi
Latest Posts
Article information

Author: Greg O'Connell

Last Updated:

Views: 5688

Rating: 4.1 / 5 (62 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Greg O'Connell

Birthday: 1992-01-10

Address: Suite 517 2436 Jefferey Pass, Shanitaside, UT 27519

Phone: +2614651609714

Job: Education Developer

Hobby: Cooking, Gambling, Pottery, Shooting, Baseball, Singing, Snowboarding

Introduction: My name is Greg O'Connell, I am a delightful, colorful, talented, kind, lively, modern, tender person who loves writing and wants to share my knowledge and understanding with you.