The Wayback Machine - https://web.archive.org/web/20241119104259/https://www.geeksforgeeks.org/python-add-space-between-numbers-and-alphabets-in-string/
Open In App

Python – Add space between Numbers and Alphabets in String

Last Updated : 24 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python‘s powerful string manipulation capabilities.

Input: test_str = 'ge3eks4geeks is1for10geeks'
Output: ge 3 eks 4 geeks is 1 for 10 geeks 
Explanation: Numbers separated from Characters. 

Adding Spaces between Numbers and Alphabets in Python

Below is the lists of methods that we can use to solve the following problem:

Add space between Numbers and Alphabets Using replace() method

When u find a numeric character within a string replace that character with a space appended on the left and right.

Python3




# initializing string
test_str = 'ge3eks4geeks'
 
# printing original String
print("The original string is : " + str(test_str))
num="0123456789"
for i in test_str:
    if i in num:
        test_str=test_str.replace(i," "+i+" ")
res=test_str
# printing result
print("The space added string : " + str(res))


Output

The original string is : ge3eks4geeks
The space added string : ge 3 eks 4 geeks


Time Complexity: O(n)
Auxiliary Space: O(n)

Add space between Numbers and Alphabets using isdigit() and  replace() methods

Here we use isdigit() the method to identify numeric characters and then we use replace() method to replace the value with the desired space needed.

Python3




# initializing string
test_str = 'ge3e1ks4geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
for i in test_str:
    if i.isdigit():
        test_str=test_str.replace(i," "+i+" ")
         
res=test_str
 
# printing result
print("The space added string : " + str(res))


Output

The original string is : ge3e1ks4geeks
The space added string : ge 3 e 1 ks 4 geeks


Time complexity : O(n), where n is length of test_str
Auxiliary space: O(n), where n is the length of the res string.

Inserting space between numbers and letters using List Comprehension

In this, we use list comprehension to add space between numbers and alphabets

Python3




test_str = 'ge3e1ks4geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
res = "".join([" "+i + " " if i.isdigit() else i for i in test_str])
 
# printing result
print("The space added string : " + str(res))


Output

The original string is : ge3e1ks4geeks
The space added string : ge 3 e 1 ks 4 geeks


Time Complexity: O(n)
Auxiliary Space: O(n)

Inserting space between number and letter using Regex with Lambda

In this, we perform the task of finding alphabets by appropriate regex, and then sub() is used to do replacements, and lambda does the task of adding spaces in between.

Python3




import re
 
# initializing string
test_str = 'geeks4geeks is1for10geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# using sub() to solve the problem, lambda used to add spaces
res = re.sub("[A-Za-z]+", lambda ele: " " + ele[0] + " ", test_str)
 
# printing result
print("The space added string : " + str(res))


Output

The original string is : geeks4geeks is1for10geeks
The space added string :  geeks 4 geeks   is 1 for 10 geeks 


Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n), where n is the length of the input string.

Inserting space between number and letter using regex with sub()

In this, we look for numerics rather than alphabets to perform the task of segregation, a similar approach by using numerics are search criteria to add spaces.

Python3




import re
 
# initializing string
test_str = 'geeks4geeks is1for10geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# using sub() to solve the problem, lambda used to add spaces
res = re.sub('(\d+(\.\d+)?)', r' \1 ', test_str)
 
# printing result
print("The space added string : " + str(res))


Output

The original string is : geeks4geeks is1for10geeks
The space added string : geeks 4 geeks is 1 for 10 geeks


Time Complexity: O(n), where n is the length of the input string.
Space Complexity: O(n), where n is the length of the input string.

Add Space between numbers and letters using isdigit and isalpha methods

Initialize a test string and an empty result string. Print the original string then loop through the test string character by character using a for loop. For each character in the test string, check if the current character is a digit and the previous character is an alphabet If the conditions in step 4 are true, add a space to the result string then check if the current character is an alphabet and the previous character is a digit if the conditions in step 6 are true, add a space to the result string then add the current character to the result string and print the result string.

Python3




test_str = 'geeks4geeks is1for10geeks'
result = ''
# printing original String
print("The original string is : " + str(test_str))
 
# loop through the test string character by character
for i in range(len(test_str)):
    # check if the current character is a digit and the previous character is an alphabet
    if test_str[i].isdigit() and result and result[-1].isalpha():
        # if so, add a space to the result string
        result += ' '
 
    # check if the current character is an alphabet and the previous character is a digit
    elif test_str[i].isalpha() and result and result[-1].isdigit():
        # if so, add a space to the result string
        result += ' '
 
    # add the current character to the result string
    result += test_str[i]
 
print(result)


Output

The original string is : geeks4geeks is1for10geeks
geeks 4 geeks is 1 for 10 geeks


Time complexity: O(n), where n is the length of the input string.
Space complexity: O(n), where n is the length of the input string.

Add Space between numbers and letters using ord() and replace() methods

Check whether the character is a digit using ord() and then replace the digit in a string by adding space front and back to that digit then display the replaced string

Python3




# initializing string
test_str = 'ge3eks4geeks'
 
# printing original String
print("The original string is : " + str(test_str))
digs=[48, 49, 50, 51, 52, 53, 54, 55, 56, 57]
for i in test_str:
    if ord(i) in digs:
        test_str=test_str.replace(i," "+i+" ")
res=test_str
# printing result
print("The space added string : " + str(res))


Output

The original string is : ge3eks4geeks
The space added string : ge 3 eks 4 geeks


Time Complexity : O(n)
Auxiliary Space: O(n)

Inserting space between number and letter using regular expressions and re.sub()

We initialize the input string “test_str” with the given string “ge3eks4geeks” and then use the re.sub() method to search for a pattern of one or more digits in the input string. The pattern is defined using the regular expression ‘(\d+)’, which matches one or more digits. The second argument to the re.sub() method is a replacement string. Here, we use r’ \1 ‘ as the replacement string, which adds a space before and after the matched digits. Finally, the re.sub() method returns the modified string “res”.

Python3




import re
 
# initializing string
test_str = 'ge3eks4geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# Using regular expressions to add space between numbers and alphabets.
res = re.sub('(\d+)', r' \1 ', test_str)
 
# printing result
print("The space added string : " + str(res))


Output

The original string is : ge3eks4geeks
The space added string : ge 3 eks 4 geeks


Time complexity: O(n), where n is the length of the input string “test_str”. The regular expression matching takes linear time in the length of the string. 
Auxiliary space: O(n), as we create a new string “res” to store the modified string.

Inserting space between number and letter using the Recursive method

If the input string test_str is empty, return an empty string. If the first character of test_str is a digit, add a space before and after the digit, and then recursively call the function on the remaining string. If the first character is not a digit, simply append it to the result of the recursive call on the remaining string. Return the result.

Python3




def add_space_recursive(test_str):
    if not test_str:
        return ""
    elif test_str[0].isdigit():
        return " " + test_str[0] + " " + add_space_recursive(test_str[1:])
    else:
        return test_str[0] + add_space_recursive(test_str[1:])
 
test_str = 'ge3eks4geeks'
 
print("The original string is : " + str(test_str))
result = add_space_recursive(test_str)
 
print("The space added string : " + str(result))


Output

The original string is : ge3eks4geeks
The space added string : ge 3 eks 4 geeks


Time complexity: O(n), where n is the length of the input string test_str.
Space complexity: O(n), where n is the length of the input string test_str.

Inserting space between number and letter using group by

Initialize an empty list to store the groups. Use a for loop to iterate through each character in the string. Use the groupby function from itertools module to group the consecutive digits together and add a space before and after the digits. Append each group to the list. then use the join method to combine the list into a single string.

Python3




from itertools import groupby
 
# initializing string
test_str = 'geeks4geeks is1for10geeks'
 
# printing original String
print("The original string is : " + str(test_str))
 
# using groupby() and isdigit() to solve the problem
res = ''.join([' ' + i + ' ' if i.isdigit() else i for k, g in groupby(test_str) for i in g])
 
# printing result
print("The space added string : " + str(res))
#This code is contributed by Pushpa


Output

The original string is : geeks4geeks is1for10geeks
The space added string : geeks 4 geeks is 1 for 1  0 geeks


Time Complexity: O(n) The time complexity of this solution is O(n) because we are iterating through each character in the string once.
Auxiliary Space: O(n) The space complexity of this solution is also O(n) because we are creating a list to store the groups, which can have a maximum length of n.



Similar Reads

Count of ways to rearrange N digits and M alphabets keeping all alphabets together
Given two positive integers N and M representing the count of distinct digits and alphabets respectively in a string, the task to count the number of ways to rearrange the characters of the string such that all the alphabets are adjacent. Examples: Input: N = 2, M = 2Output: 12Explanation: Possible ways to rearrange characters of a string such that
9 min read
Python - Differential Sort String Numbers and Alphabets
Given a List String, Reorder List, with Sorted Alphabets followed by Sorted Strings. Input : test_list = ["1", "G", "10", "L", "9", "K", "4"] Output : ['G', 'K', 'L', '1', '4', '9', '10'] Explanation : Alphabets sorted, succeeded by sorted digits. Input : test_list = ["1", "G", "10", "L", "9"] Output : ['G', 'L', '1', '9', '10'] Explanation : Alpha
5 min read
Python Program to test if the String only Numbers and Alphabets
Given a String, our task is to write a Python program to check if string contains both numbers and alphabets, not either nor punctuations. Examples: Input : test_str = 'Geeks4Geeks' Output : True Explanation : Contains both number and alphabets. Input : test_str = 'GeeksforGeeks' Output : False Explanation : Doesn't contain number. Method #1 : Usin
4 min read
Python program to separate alphabets and numbers in a string
Given a string containing numbers and alphabets, the task is to write a Python program to separate alphabets and numbers from a string using regular expression. Examples Input: abcd11gdf15hnnn678hh4 Output: 11 15 678 4 abcd gdf hnnn hh Explanation: The string is traversed from left to right and number and alphabets are separated from the given stri
4 min read
Python - Find Words with both alphabets and numbers
Sometimes, while working with Python strings, we can have problem in which we need to extract certain words with contain both numbers and alphabets. This kind of problem can occur in many domains like school programming and web-development. Lets discuss certain ways in which this task can be performed. Method #1 : Using any() + isdigit() + isalpha(
6 min read
Python | Test if String contains Alphabets and Spaces
Sometimes, while testing of credibility of string being a part of containing just alphabets, an exception of spaces has to be mentioned explicitly and becomes a problem. This can occur in domains that deal with data. Lets discuss certain ways in which this task can be performed. Method #1 : Using all() + isspace() + isalpha() This is one of the way
5 min read
Python - Add Space between Potential Words
Given list of Strings, task is to add a space before sequence which begin with capital letters. Input : test_list = ["gfgBest", "forGeeks", "andComputerScienceStudents"] Output : ['gfg Best', 'for Geeks', 'and Computer Science Students'] Explanation : Words segregated by Capitals. Input : test_list = ["ComputerScienceStudentsLoveGfg"] Output : ['Co
7 min read
PyCairo - Transform a distance vector from device space to user space
In this article, we will learn how we can transform a distance-vector from device space to user space using PyCairo in python. This function is similar to Context.device_to_user() except that the translation components of the inverse CTM will be ignored when transforming (dx,dy). Pycairo is a Python module providing bindings for the cairo graphics
2 min read
PyCairo - How we Can transform a coordinate from device space to user space ?
In this article, we will learn how we Can transform a coordinate from device space to user space using PyCairo in python. Transform a coordinate from device space to user space by multiplying the given point by the inverse of the current transformation matrix (CTM). Pycairo is a Python module providing bindings for the cairo graphics library. This
2 min read
Add space between histogram bars in Matplotlib
Matplotlib is a plotting library in Python programming language and it's by default numerical mathematics extension of NumPy library in python language. While programming in python language we use the matplotlib library package for graph and histogram visualizations. But while plotting histogram using matplotlib in python, it lacks division or spac
2 min read
Python | Ways to initialize list with alphabets
While working with Python lists, sometimes we wish to initialize the list with the English alphabet a-z or A-Z. This is an essential utility in competitive programming and also in certain applications. Let's discuss various methods to achieve this using Python. Initialize the list with alphabets using string.ascii_uppercase The most pythonic and la
3 min read
Python | Print Alphabets till N
Sometimes, while working with Python, we can have a problem in which we need to print the specific number of alphabets in order. This can have application in school-level programming. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loop + chr() This is brute force way to perform this task. In this, we iterate the e
6 min read
Python | Extract Strings with only Alphabets
Sometimes, while working with Python lists, we can have a problem in which we need to extract only those strings which contain only alphabets and discard those which include digits. This has applications in day-day programming and web development domain. Lets discuss certain ways in which this task can be performed. Method #1 : Using isalpha() + li
7 min read
Python program to generate a list of alphabets in lexical order
Prerequisite: chr() The following methods explain how a python list with alphabets in lexical(alphabetic) order can be generated dynamically using chr() method. Approach: The core of the concept in both methods is almost same, they only differ in implementation: Validate size of alphabet list(size=26).If size>26, change to 26.If size≤0, no meani
3 min read
Python - Extract Strings with Successive Alphabets in Alphabetical Order
Given a string list, extract list which has any succession of characters as they occur in alphabetical order. Input : test_list = ['gfg', 'ij', 'best', 'for', 'geeks'] Output : ['ij', 'gfg', 'best'] Explanation : i-j, f-g, s-t are consecutive pairs. Input : test_list = ['gf1g', 'in', 'besht', 'for', 'geeks'] Output : [] Explanation : No consecutive
5 min read
Python - Filter rows with only Alphabets from List of Lists
Given Matrix, write a Python program to extract rows which only contains alphabets in its strings. Examples: Input : test_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"], ["Gfg is good"], ["love", "gfg"]] Output : [['gfg', 'is', 'best'], ['love', 'gfg']] Explanation : All strings with just alphabets are extracted. Input : test_list = [["gfg"
5 min read
Python Program to Rearrange positive and negative numbers in O(n) time and O(1) extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that positive and negative numbers are placed alternatively. Number of positive and negative numbers need not be equal. If there are more positive numbers they appear at the end of the array. If there are more negative numbers, they too appear in t
3 min read
Program to Print K using Alphabets
Given a number n, the task is to print 'K' using alphabets.Examples: Input: n = 5 Output: A B C D E F A B C D E A B C D A B C A B A A A B A B C A B C D A B C D E A B C D E F Input: n = 3 Output: A B C D A B C A B A A A B A B C A B C D Below is the implementation. C/C++ Code // C++ Program to design the // above pattern of K using alphabets #include
5 min read
Python | Convert list of strings to space separated string
Given a list of strings, write a Python program to convert the given list of strings into a space-separated string. Examples: Input : ['geeks', 'for', 'geeks'] Output : geeks for geeks Input : ['Python', 'Language'] Output : Python Language Approach #1 : Python string translate() The string translate() method returns a string where each character i
4 min read
Python - All possible space joins in String
Sometimes, while working with Python Strings, we can have a problem in which we need to construct strings with a single space at every possible word ending. This kind of application can occur in domains in which we need to perform testing. Let us discuss certain ways in which this task can be performed. Method #1: Using loop + join() This is a brut
8 min read
Python | Add comma between numbers
Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let's discuss certain ways in which this task can be performed. Method #1 : Using str.format() The string format function can be used by supplying the valid formatter to per
5 min read
Python - Remove space between tuple elements
Sometimes, while working with Tuples, we can have a problem in which we need to print tuples, with no space between the comma and next element, which by convention, is present. This problem can have use in day-day and school programming. Let's discuss certain ways in which this task can be performed. Input : test_tuple = (7, 6, 8) Output : (7, 6, 8
6 min read
Set the amount of vertical space between legend groups using Plotly-Python
In this article, we will learn how to set the amount of vertical space between legend groups. A legend is an area describing the elements of the graph. In the plotly legend is used to Place a legend on the axes. Example 1: In this Bar chart, We are setting the amount of vertical space (in px) between legend groups with the help of a method called f
1 min read
Extract numbers from a text file and add them using Python
Python too supports file handling and allows users to handle files i.e., to read and write files, along with many other file handling options, to operate on files. Data file handling in Python is done in two types of files: Text file (.txt extension) Binary file (.bin extension) Here we are operating on the .txt file in Python. Through this program
4 min read
How to insert a space between characters of all the elements of a given NumPy array?
In this article, we will discuss how to insert a space between the characters of all elements of a given array of string. Example: Suppose we have an array of string as follows: A = ["geeks", "for", "geeks"] then when we insert a space between the characters of all elements of the above array we get the following output. A = ["g e e k s", "f o r",
1 min read
Count pairs of points having distance between them equal to integral values in a K-dimensional space
Given an array points[] representing N points in a K-dimensional space, the task is to find the count of pairs of points in the space such that the distance between the points of each pair is an integer value. Examples: Input: points[] = { {1, 2}, {5, 5}, {2, 8} }, K = 2Output: 1Explanation: Distance between points of the pair(points[0], points[1])
7 min read
Python | Same and Different value space
In Python, we have same pool for similar values, even if they share different variables. This has many advantages, that it saves a lot of memory arranging different spaces for similar values. This is provided for small integers. But there are ways in which we can have same and different pool values. Lets discuss certain cases of the same. Case #1 :
3 min read
Python Program to find volume, surface area and space diagonal of a cuboid
Given the length, base, and height of a cuboid. The task is to find the Surface Area, Volume and space diagonal of the cuboid. Examples: Input : length = 9 breadth = 6 height = 10 Output : Surface area = 408 volume = 540 space diagonal = 14.73 Input : length = 5 breadth = 4 height = 3 Output : surface area = 94 volume = 60 space diagonal = 7.07 For
2 min read
Python Program For Cloning A Linked List With Next And Random Pointer In O(1) Space
Given a linked list having two pointers in each node. The first one points to the next node of the list, however, the other pointer is random and can point to any node of the list. Write a program that clones the given list in O(1) space, i.e., without any extra space. Examples: Input : Head of the below-linked list Output : A new linked list ident
4 min read
Python program to add two binary numbers
Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum becomes more than 1, then store carry for the next digit
4 min read
Practice Tags :
three90RightbarBannerImg