Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python | Split String by Number

#1
Python | Split String by Number

Rate this post

✨Summary: To split a string by a number, use the regex split method using the “\d” pattern.

Minimal Example


my_string = "#@1abc3$!*5xyz" # Method 1
import re res = re.split('\d+', my_string)
print(res) # Method 2
import re res = re.findall('\D+', my_string)
print(res) # Method 3
from itertools import groupby li = [''.join(g) for _, g in groupby(my_string, str.isdigit)]
res = [x for x in li if x.isdigit() == False]
print(res) # Method 4
res = []
for i in my_string: if i.isdigit() == True: my_string = my_string.replace(i, ",")
print(my_string.split(",")) # Outputs:
# ['#@', 'abc', '$!*', 'xyz']

Problem Formulation


?Problem: Given a string containing different characters. How will you split the string whenever a number appears?

Method 1: re.split()


The re.split(pattern, string) 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, re.split('a', 'bbabbbab') results in the list of strings ['bb', 'bbb', 'b'].

Code:

import re
my_string = "#@1abc3$!*5xyz"
res = re.split('\d+', my_string)
print(res) # ['#@', 'abc', '$!*', 'xyz']

Explanation: The \d special character matches any digit between 0 and 9. By using the maximal number of digits as a delimiter, you split along the digit-word boundary. 

Method 2: re.findall()


The re.findall(pattern, string) method scans 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.

Code:

import re
my_string = "#@1abc3$!*5xyz"
res = re.findall('\D+', my_string)
print(res) # ['#@', 'abc', '$!*', 'xyz']

Explanation: The \special character matches all characters except any digit between 0 and 9. Thus, you are essentially finding all character groups that appear before the occurrence of a digit.

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.

Method 3: itertools.groupby()


Code:

from itertools import groupby
my_string = "#@1abc3$!*5xyz"
li = [''.join(g) for _, g in groupby(my_string, str.isdigit)]
res = [x for x in li if x.isdigit() == False]
print(res) # ['#@', 'abc', '$!*', 'xyz']

Explanation:

  • The itertools.groupby(iterable, key=None) function creates an iterator that returns tuples (key, group-iterator) grouped by each value of key. We use the str.isdigit() function as key function.
  • The str.isdigit() function returns True if the string consists only of numeric characters. Thus, you will have a list created by using numbers as separators. Note that this list will also contain the numbers as items within it.
  • In order to eliminate the numbers, use another list comprehension that checks if an element in the list returned previously is a digit or not with the help of the isdigit method. If it is a digit, the item will be discarded. Otherwise it will be stored in the list.

Method 4: Replace Using a for Loop


Approach: Use a for loop to iterate through the characters of the given string. Check if a character is a digit or not. As soon as a digit is found, replace that character/digit with a delimiter string ( we have used a comma here) with the help of the replace() method. This basically means that you are placing a particular character in the string whenever a number appears. Once all the digits are replaced by the separator string, split the string by passing the separator string as a delimiter to the split method.

Code:

my_string = "#@1abc3$!*5xyz"
res = []
for i in my_string: if i.isdigit(): my_string = my_string.replace(i, ",")
print(my_string.split(",")) # ['#@', 'abc', '$!*', 'xyz']

Conclusion


Phew! We have successfully solved the given problem and managed to do so using four different ways. I hope you found this article helpful and it answered your queries. Please subscribe and stay tuned for more solutions and tutorials.

Happy coding! ?

?Related Read: How to Split a String Between Numbers and Letters?



https://www.sickgaming.net/blog/2022/12/...by-number/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Python Int to String with Trailing Zeros xSicKxBot 0 33 12-01-2025, 05:47 PM
Last Post: xSicKxBot
  [Tut] Wrap and Truncate a String with Textwrap in Python xSicKxBot 0 2,054 09-01-2023, 07:45 PM
Last Post: xSicKxBot
  [Tut] Write a Long String on Multiple Lines in Python xSicKxBot 0 1,500 08-17-2023, 11:05 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,555 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,694 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,416 08-10-2023, 09:24 PM
Last Post: xSicKxBot
  [Tut] [Fixed] Access Denied – OpenAI Error Reference Number 1020 xSicKxBot 0 1,387 05-25-2023, 04:45 PM
Last Post: xSicKxBot
  [Tut] F-String Python Hex, Oct, and Bin: Efficient Number Conversions xSicKxBot 0 1,667 03-28-2023, 12:01 PM
Last Post: xSicKxBot
  [Tut] How to Correctly Write a Raw Multiline String in Python: Essential Tips xSicKxBot 0 1,491 03-27-2023, 05:54 PM
Last Post: xSicKxBot
  [Tut] How To Extract Numbers From A String In Python? xSicKxBot 0 1,316 02-26-2023, 02:45 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016