Python | Splitting Text and Number in string
Sometimes, we have a string, which is composed of text and number (or vice-versa), without any specific distinction between the two. There might be a requirement in which we require to separate the text from the number. Let’s discuss certain ways in which this can be performed.
Method #1 : Using re.compile() + re.match() + re.groups()
The combination of all the above regex functions can be used to perform this particular task. In this we compile a regex and match it to group text and numbers separately into a tuple.
# Python3 code to demonstrate working of # Splitting text and number in string # Using re.compile() + re.match() + re.groups() import re # initializing string test_str = "Geeks4321" # printing original string print("The original string is : " + str(test_str)) # Using re.compile() + re.match() + re.groups() # Splitting text and number in string temp = re.compile("([a-zA-Z]+)([0-9]+)") res = temp.match(test_str).groups() # printing result print("The tuple after the split of string and number : " + str(res)) |
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')
Method #2 : Using re.findall()
The slight modification of regex can provide the flexibility to reduce the number of regex functions required to perform this particular task. The findall function is alone enough for this task.
# Python3 code to demonstrate working of # Splitting text and number in string # Using re.findall() import re # initializing string test_str = "Geeks4321" # printing original string print("The original string is : " + str(test_str)) # Using re.findall() # Splitting text and number in string res = [re.findall(r'(\w+?)(\d+)', test_str)[0] ] # printing result print("The tuple after the split of string and number : " + str(res)) |
The original string is : Geeks4321
The tuple after the split of string and number : ('Geeks', '4321')
Recommended Posts:
- Python | Splitting operators in String
- Python | Splitting string to list of characters
- Python | Splitting string list by strings
- Python | Splitting string to list of characters
- Python | Splitting list on empty string
- Text Analysis in Python 3
- Text Preprocessing in Python | Set 2
- Python | Insert a number in string
- Convert Text to Speech in Python
- Python PIL | ImageDraw.Draw.text()
- Python | Merge two text files
- Tokenize text using NLTK in python
- Python | Tokenize text using TextBlob
- The most occurring number in a string using Regex in python
- Python | Scramble words from a text file
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



