Adding space between Numbers and Alphabets in Strings using Python

When working with strings that contain a combination of numbers and alphabets, it can be beneficial to insert a space between the numbers and alphabets. Adding this space can improve the readability and formatting of the string, making it easier to interpret and work with.

Python provides powerful tools for string manipulation through the re module, which is built-in for working with regular expressions. Regular expressions allow us to match and manipulate strings based on specific patterns, making them ideal for solving this task.

Note: The re module is part of Python's standard library, so no installation is required.

Basic Implementation

Let's start with a simple function that adds space between single alphabets and single digits ?

import re

def add_space_between_numbers_and_alphabets(string):
    pattern = r'([a-zA-Z])(\d)'
    replacement = r'\1 \2'
    modified_string = re.sub(pattern, replacement, string)
    return modified_string

# Test with sample inputs
string1 = "abc123"
result1 = add_space_between_numbers_and_alphabets(string1)
print(result1)

string2 = "xyz456def"
result2 = add_space_between_numbers_and_alphabets(string2)
print(result2)
abc 123
xyz 456def

The regular expression pattern r'([a-zA-Z])(\d)' matches a single alphabet followed by a single digit using two capturing groups. The replacement pattern r'\1 \2' adds a space between the captured groups.

Handling Multiple Instances

To handle multiple instances of alphabet-digit combinations, we can use a callback function with re.sub() ?

import re

def add_space_between_numbers_and_alphabets(string):
    pattern = r'([a-zA-Z])(\d)'
    
    def add_space(match):
        return match.group(1) + ' ' + match.group(2)
    
    modified_string = re.sub(pattern, add_space, string)
    return modified_string

# Test with multiple instances
string = "abc123xyz456"
result = add_space_between_numbers_and_alphabets(string)
print(result)
abc 123xyz 456

Handling Different Formats

For more flexible matching of multiple consecutive alphabets and digits, we can modify the pattern ?

import re

def add_space_comprehensive(string):
    # Match alphabets followed by digits
    pattern1 = r'([a-zA-Z]+)(\d+)'
    # Match digits followed by alphabets
    pattern2 = r'(\d+)([a-zA-Z]+)'
    
    # Add space between alphabets and digits
    modified_string = re.sub(pattern1, r'\1 \2', string)
    # Add space between digits and alphabets
    modified_string = re.sub(pattern2, r'\1 \2', modified_string)
    
    return modified_string

# Test with different formats
string1 = "abc123xyz456"
result1 = add_space_comprehensive(string1)
print(f"Input: {string1}")
print(f"Output: {result1}")

string2 = "123abc456xyz"
result2 = add_space_comprehensive(string2)
print(f"Input: {string2}")
print(f"Output: {result2}")

string3 = "test123data456end"
result3 = add_space_comprehensive(string3)
print(f"Input: {string3}")
print(f"Output: {result3}")
Input: abc123xyz456
Output: abc 123 xyz 456
Input: 123abc456xyz
Output: 123 abc 456 xyz
Input: test123data456end
Output: test 123 data 456 end

One-Step Solution

We can combine both patterns into a single regex for a more efficient solution ?

import re

def add_spaces_optimized(string):
    # Match transitions between letters and digits in both directions
    pattern = r'([a-zA-Z])(\d)|(\d)([a-zA-Z])'
    
    def replace_match(match):
        if match.group(1) and match.group(2):  # letter followed by digit
            return match.group(1) + ' ' + match.group(2)
        else:  # digit followed by letter
            return match.group(3) + ' ' + match.group(4)
    
    return re.sub(pattern, replace_match, string)

# Test the optimized solution
test_strings = ["abc123", "123abc", "test123data456end", "mixed123text456"]

for test_str in test_strings:
    result = add_spaces_optimized(test_str)
    print(f"'{test_str}' ? '{result}'")
'abc123' ? 'abc 123'
'123abc' ? '123 abc'
'test123data456end' ? 'test 123 data 456 end'
'mixed123text456' ? 'mixed 123 text 456'

Comparison

Method Pattern Best For
Basic ([a-zA-Z])(\d) Single letter-digit transitions
Comprehensive ([a-zA-Z]+)(\d+) Multiple consecutive letters/digits
Optimized ([a-zA-Z])(\d)|(\d)([a-zA-Z]) Both directions in one pass

Conclusion

Use the re module with appropriate patterns to add spaces between numbers and alphabets in strings. The optimized solution handles both letter-to-digit and digit-to-letter transitions efficiently in a single pass.

Updated on: 2026-03-27T12:34:17+05:30

904 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements