Contents
Python – Split String by Underscore
You can split a string in Python using String.split() method.
In this tutorial, we will learn how to split a string by underscore _
in Python using String.split() and re.split() methods.
Refer Python Split String to know the syntax and basic usage of String.split() method.
Example 1: Split String by Underscore
In this example, we will take a string with items/words separated by underscore character _
, split the string and store the items in a list.
Python Program
str = '52_841_63_24_76_49'
#split string by _
items = str.split('_')
print(items)
Run Output
['52', '841', '63', '24', '76', '49']
Example 2: Split String by One or More Underscores
In this example, we will take a string with items/words separated by one or more underscore characters, split the string and store the items in a list.
We shall use re
python package in the following program. re.split(regular_expression, string)
returns list of items split from string
based on the regular_expression
.
Python Program
import re
str = '52_841__63____24_76______49'
#split string by _
items = re.split('_+', str)
print(items)
Run Regular Expression _+
represents one or more underscores. So, one or more underscores is considered as a delimiter.
Output
['52', '841', '63', '24', '76', '49']
One ore more adjacent underscores are considered as a single delimiter.
Summary
In this tutorial of Python Examples, we learned how to split a string by underscore using String.split() and re.split() methods.