Change language

Python | Split multiple characters from string

| | |

While coding or improvising your programming skills, you’ve probably come across many scenarios where you would like to use .split() in Python so as not to split just one character , but several characters at the same time. Consider this for an example:

 "GeeksforGeeks, is an-awesome! Website" 

Using .split() for the above above will result in

 [’GeeksforGeeks,’, ’is’,’ an-awesome! ’,’ website’] 

whereas the desired result should be

 [’GeeksforGeeks’,’ is’, ’an’,’ awesome’, ’website’] 

In this article, we’ll look at some of the ways we can achieve the same.

Using re.split ()

This is the most efficient and commonly used method of splitting multiple characters at the same time. A regular expression (regular expressions) is used for this.

# Python3 code to demonstrate how it works
# Line splitting operators
# Using re.split ()

 

import re

  
# initialization string

data = " GeeksforGeeks, is_an-awesome! website "

  
# print original line

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

  
# Using re.split ()
# Splitting characters in a line

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

  
# print result

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’]

Line re. split (& # 39 ;, | _ | - |! & # 39 ;, data) tells Python to split the variable’s data into characters: either _ or or! , The character “ | Represents or.

There are several characters in a regular expression that are treated as special characters and have different functions. If you want to strip such a character, you need to escape it using " / " (backslash). Here is a list of special characters to escape before using them:

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

For example :

import re

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

  
# To separate & quot; + & quot; use a backslash

print (re.split ( ’, | _ | - |! | + ’ , newData))

Exit:

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

Note. To learn more about regular expressions, click here .

Using re.findall ()

This is a little more cryptic, but saves time. It also uses regex as described above, but instead of the .split() method, it uses a method named .findall () . This method finds all matching instances and returns each one in the list. This delimiting method is best used when you don’t know exactly what characters you want to delimit.

# Python3 code to demonstrate how it works
# Line splitting operators
# Using re.findall ()

import re

  

 
# initialization string

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

 
# print original line

print ( "The origin al string is: " + data) 

  
# Using re.findall ()
# Separating characters in a line

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

 
# print result

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

Exit:

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

Here the keyword [/ w & # 39;] + indicates that it will find everything instances of alphabets or will underline (_) one or more and return them in a list. 
Note: [/ w & # 39;] + is not split into underscores ( _ ) as it looks for alphabets and underscores ... 
For example :

import re

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

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

Exit :

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

Using replace () and split ()

This is a very new way to split. It does not use regular expressions and is inefficient, but still worth a try. If you know the characters you want to split characters into, just replace them with a space and then use .split() :

# Python code for demo
# split lines

 
# Leading line

data = "Let’s_try, this now"

 
# print original line

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

 
# Using replace () and s plit ()
# Separating characters in a line

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

 
# Print result

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

Exit:

The original string is: Let’s_try, this now
The list after split functionality: [“Let’s performing”, ’t ry ’,’ this’, ’now’]

Character Classes

Regex Character Description Cheat Sheet

Shorthand character class Represents
d Any numeric digit from 0 to 9
D Any character that is not a numeric digit from 0 to 9
w Any letter, numeric digit, or the underscore character
W Any character that is not a letter, numeric digit, or the underscore character
s Any space, tab, or newline character
S Any character that is not a space, tab, or newline

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically