Friday, December 27, 2024
Google search engine
HomeLanguagesPython | Splitting Text and Number in string

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




# 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))


Output

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




# 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))


Output

The original string is : Geeks4321
The tuple after the split of string and number : [('Geeks', '4321')]

Method #3: Using isdigit() method

Python3




# Python3 code to demonstrate working of
# Splitting text and number in string
 
# initializing string
test_str = "Geeks4321"
 
# printing original string
print("The original string is : " + str(test_str))
 
 
# Splitting text and number in string
text=""
numbers=""
res=[]
for i in test_str:
    if(i.isdigit()):
        numbers+=i
    else:
        text+=i
res.append(text)
res.append(numbers)
 
# printing result
print("The tuple after the split of string and number : " + str(res))


Output

The original string is : Geeks4321
The tuple after the split of string and number : ['Geeks', '4321']

Method #4 : Without any builtin methods

Python3




# Python3 code to demonstrate working of
# Splitting text and number in string
 
# initializing string
test_str = "Geeks4321"
 
# printing original string
print("The original string is : " + str(test_str))
 
 
# Splitting text and number in string
text=""
numbers=""
digits="0123456789"
res=[]
for i in test_str:
    if(i in digits):
        numbers+=i
    else:
        text+=i
res.append(text)
res.append(numbers)
 
# printing result
print("The tuple after the split of string and number : " + str(res))


Output

The original string is : Geeks4321
The tuple after the split of string and number : ['Geeks', '4321']

The time complexity of this solution is O(n) since it involves iterating over each character in the input string.

 The auxiliary space complexity is also O(n) since we need to store the text and number parts in separate strings before adding them to the result list.

Method 5: Using the “isnumeric()” method and list comprehension.

  1. Initialize the string “test_str” with some alphanumeric characters.
  2. Print the original string using the “print()” function.
  3. Create a list comprehension that iterates over each character in the string “test_str” and checks if the character is numeric using the “isnumeric()” method.
  4. Use the “join()” method to convert the list comprehension result into a string and assign it to a variable called “numbers”.
  5. Create a new string called “text” that is the original string with all the numeric characters removed by iterating over each character in the string “test_str” using a for loop and checking if the character is alphabetic using the “isalpha()” method.
  6. Append the “text” and “numbers” strings as a tuple to a list called “res”.
  7. Print the tuple after the split of string and number using the “print()” function.
     

Python3




# Python3 code to demonstrate working of
# Splitting text and number in string
 
# initializing string
test_str = "Geeks4321"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Splitting text and number in string
numbers = "".join([char for char in test_str if char.isnumeric()])
text = "".join([char for char in test_str if char.isalpha()])
res = [(text, numbers)]
 
# printing result
print("The tuple after the split of string and number : " + str(res))


Output

The original string is : Geeks4321
The tuple after the split of string and number : [('Geeks', '4321')]

The time complexity of this method is O(n), where n is the length of the input string.
The auxiliary space complexity of this method is O(n), where n is the length of the input string.

Method 6: Using reduce():

Algorithm:

  1. Import the reduce function from the functools module.
  2. Define a string test_str containing the input string.
  3. Define a lambda function that takes two arguments: a tuple acc and a character char.
  4. The lambda function checks if the character char is a letter or a number. If it is a letter, it appends the character to the first string in the tuple. If it is a number, it appends the character to the second string in the tuple.
  5. Call the reduce function with the lambda function, the input string test_str, and an initial value of the tuple (“”, “”).
  6. The reduce function applies the lambda function cumulatively to the characters of the input string, and returns the final value of the tuple containing the split text and number strings.
  7. Wrap the resulting tuple in a list with a single element to match the output format of the original code.
  8. Print the resulting list.
     

Python3




from functools import reduce
 
test_str = "Geeks4321"
# printing original string
print("The original string is : " + str(test_str))
res = reduce(lambda acc, char: (acc[0] + char, acc[1]) if char.isalpha() else (acc[0], acc[1] + char), test_str, ("", ""))
 
res = [(res[0], res[1])]
 
print("The tuple after the split of string and number : " + str(res))
#This code is contrinuted by Pushpa.


Output

The original string is : Geeks4321
The tuple after the split of string and number : [('Geeks', '4321')]

The time complexity :O(n), where n is the length of the input string, because the lambda function is applied to each character of the string exactly once.

 The space complexity :O(n), because the size of the tuple is proportional to the length of the input string. 

Method 7: Using heapq:

Algorithm:

  1. Initialize an empty string for text and numbers.
  2. Iterate over each character in the given string.
  3. If the character is an alphabet, append it to the text string.
  4. If the character is a number, append it to the numbers string.
  5. Create a tuple containing the text and numbers string.
  6. Check if the text and numbers strings are non-empty and append the tuple to the result list.
  7. Return the result list.

Python3




# Python3 code to demonstrate working of
# Splitting text and number in string
# using heapq
 
import heapq
 
# initializing string
test_str = "Geeks4321"
 
# printing original string
print("The original string is : " + str(test_str))
 
# Splitting text and number in string using heapq
text = ''
numbers = ''
for char in test_str:
    if char.isalpha():
        text += char
    elif char.isnumeric():
        numbers += char
res = [(text, numbers)]
 
# Get only the first element of each tuple that contains a non-empty string
res = [(tup[0], tup[1]) for tup in res if len(tup[0]) > 0 and len(tup[1]) > 0]
 
# printing result
print("The tuple after the split of string and number : " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original string is : Geeks4321
The tuple after the split of string and number : [('Geeks', '4321')]

Time Complexity: O(n), where n is the length of the input string. We need to iterate over each character in the input string to separate the text and numbers.

Space Complexity: O(1), as we are using constant extra space to store the text and numbers strings and the result list.
 

RELATED ARTICLES

Most Popular

Recent Comments