12-02-2022, 08:43 AM
Python | Split String Hyphen
Rate this post
Summary: Use to split the given string by hyphen and store each word as an individual item in a list. Some other ways to split using hyphen include using a list comprehension and the regex library.
[b]Minimal Example[/b]
[b]Problem Formulation[/b]
Problem: Given a string, how will you split the string into a list of words using the hyphen as a delimiter?
[b]Example[/b]
Let’s understand the problem with the help of an example.
Now without any further ado, let’s dive into the numerous ways of solving this problem.
[b]Method 1: Using split()[/b]
Python’s built-in function splits the string at a given separator and returns a split list of substrings. Here’s how the function works: will split the string with the character ‘’ as the delimiter and return the following list as an output: .
Approach: To split a string by hyphen, you can simply pass the underscore as a separator to the function.
Code:
Related Read: Python String split()
[b]Method 2: Using re.split()[/b]
Another way of separating a string by using the underscore as a separator is to use the method from the regex library. The method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, results in the list of strings .
Approach: You can use the method as where returns a match whenever the string contains a hyphen. Whenever any hyphen is encountered, the text gets separated and the split substring gets stored as an element within the resultant list.
Code:
Related Read: Python Regex Split
[b]Method 3: Using filter()[/b]
Note: This approach is efficient when the resultant list contains empty strings along with substrings.
Python’s built-in function filters out the elements that pass a filtering condition. It takes two arguments: function and iterable. The function assigns a Boolean value to each element in the iterable to check whether the element will pass the filter or not. It returns an iterator with the elements that passes the filtering condition.
Approach: Use the method to split the string by hyphen. The function takes as the first argument and the list of split strings as the second argument. The function then iterates through the list and removes any empty elements. As the method returns an object, we need to use the to convert the object into a list.
Code:
Related Read: Python filter()
[b]Method 4: Using re.findall()[/b]
The method scans the string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order- when scanning the string from left to right.
Approach: You can use the method from the regex module to split the string by hyphen. Use ‘‘ as the pattern that can be fed into the function to solve the problem. It simply, means a set all characters that are joined by a hyphen will be grouped together.
Code:
Related Read: Python re.findall() – Everything You Need to Know
[b]Python | Split String by Dot[/b]
Now that we have gone through numerous ways of solving the given problem, here’s a similar programming challenge for you to solve.
Challenge: You are given a string that contains dots in it. How will you split the string using a dot as a delimiter? Consider the code below and try to split the string by dot.
Try to solve the problem yourself before looking into the given solutions.
Solution: Here are the different methods to split a string by using the dot as a delimiter/separator:
Conclusion
Hurrah! We have successfully solved the given problem using as many as four different ways. We then went on to solve a similar coding challenge. I hope this article helped you. Please subscribe and stay tuned for more interesting articles!
Happy coding!![[Image: 1f642.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png)
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
Rate this post
Summary: Use Code:
"given string".split('-')[b]Minimal Example[/b]
Code:
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red"
# Method 1
print(text.split("-"))
# Method 2
import re
print(re.split('-', text))
# Method 3
print(list(filter(None, text.split('-'))))
# Method 4
print([x for x in re.findall(r'[^-]*|(?!-).*$', text) if x != '']) # OUTPUT: ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red'][b]Problem Formulation[/b]
Problem: Given a string, how will you split the string into a list of words using the hyphen as a delimiter?[b]Example[/b]
Let’s understand the problem with the help of an example.
Code:
# Input:
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red"
# Output:
['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']Now without any further ado, let’s dive into the numerous ways of solving this problem.
[b]Method 1: Using split()[/b]
Python’s built-in
Code:
split()Code:
split()Code:
'finxterx42'.split('x')Code:
xCode:
['fin', 'ter', '42']Approach: To split a string by hyphen, you can simply pass the underscore as a separator to the
Code:
split('-')Code:
Code:
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red"
print(text.split("-")) # ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
Related Read: Python String split()[b]Method 2: Using re.split()[/b]
Another way of separating a string by using the underscore as a separator is to use the
Code:
re.split()Code:
re.split(pattern, string)Code:
re.split('a', 'bbabbbab')Code:
['bb', 'bbb', 'b']Approach: You can use the
Code:
re.split()Code:
re.split('-', text)Code:
'-'Code:
Code:
import re
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red"
print(re.split('-', text)) # ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
Related Read: Python Regex Split[b]Method 3: Using filter()[/b]
Note: This approach is efficient when the resultant list contains empty strings along with substrings.
Python’s built-in
Code:
filter()Approach: Use the
Code:
filter()Code:
NoneCode:
filter()Code:
filter()Code:
list()Code:
Code:
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red" print(list(filter(None, text.split('-')))) # ['Violet', 'Indigo', 'Blue', 'Green', 'Yellow', 'Orange', 'Red']
Related Read: Python filter()[b]Method 4: Using re.findall()[/b]
The
Code:
re.findall(pattern, string)Approach: You can use the
Code:
re.findall()Code:
[^-]|(?!-).$Code:
findallCode:
Code:
import re
text = "Violet-Indigo-Blue-Green-Yellow-Orange-Red" print([x for x in re.findall(r'[^_]*', text) if x != '']) # ['Python', 'Pycharm', 'Java', 'Eclipse', 'Golang', 'VisualStudio']
Related Read: Python re.findall() – Everything You Need to Know[b]Python | Split String by Dot[/b]
Now that we have gone through numerous ways of solving the given problem, here’s a similar programming challenge for you to solve.
Challenge: You are given a string that contains dots in it. How will you split the string using a dot as a delimiter? Consider the code below and try to split the string by dot.
Code:
# Input:
text = "stars.moon.sun.sky" # Expected Output:
['stars', 'moon', 'sun', 'sky']Try to solve the problem yourself before looking into the given solutions.
Solution: Here are the different methods to split a string by using the dot as a delimiter/separator:
Code:
text = "a*b*c"
# Method 1
print(text.split("*")) # Method 2
print(list(filter(None, text.split('*')))) # Method 3
import re
print([x for x in re.findall(r'[^/*]*|(?!/*).*$', text) if x != '']) # Method 4
print(re.split('[/*]', text))Hurrah! We have successfully solved the given problem using as many as four different ways. We then went on to solve a similar coding challenge. I hope this article helped you. Please subscribe and stay tuned for more interesting articles!
Happy coding!
![[Image: 1f642.png]](https://s.w.org/images/core/emoji/14.0.0/72x72/1f642.png)
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.

