Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to add space before and after specific character using regex in Python?
When working with text data in Python, we often need to format strings to make them more readable. Regular expressions (regex) provide a powerful way to add spaces before and after specific characters. In this article, we'll explore how to use Python's re module for this purpose.
Understanding the Regex Pattern
The key to adding spaces around characters is using the re.sub() function with the pattern r'\s*character\s*'. This pattern:
-
\s*− Matches zero or more whitespace characters before the target character -
character− The specific character we want to format -
\s*− Matches zero or more whitespace characters after the target character
Adding Spaces Around Comma
Let's add spaces before and after commas to improve readability ?
import re
# Sample string
text = "Hello,World,Python,Programming"
# Add space before and after the comma
formatted_text = re.sub(r'\s*,\s*', ' , ', text)
print("Original:", text)
print("Formatted:", formatted_text)
Original: Hello,World,Python,Programming Formatted: Hello , World , Python , Programming
Adding Spaces Around Exclamation Mark
Here we'll format exclamation marks with proper spacing ?
import re
# Sample string
text = "Hello!World!How are you!"
# Add space before and after the exclamation mark
formatted_text = re.sub(r'\s*!\s*', ' ! ', text)
print("Original:", text)
print("Formatted:", formatted_text)
Original: Hello!World!How are you! Formatted: Hello ! World ! How are you !
Adding Spaces Around Period
We can also format periods for better text structure ?
import re
# Sample string
text = "Hello.World.This is a test."
# Add space before and after the period
formatted_text = re.sub(r'\s*\.\s*', ' . ', text)
print("Original:", text)
print("Formatted:", formatted_text)
Original: Hello.World.This is a test. Formatted: Hello . World . This is a test .
Generic Function for Any Character
Here's a reusable function that can add spaces around any character ?
import re
def add_spaces_around_char(text, character):
"""Add spaces before and after a specific character."""
# Use re.escape() to handle special regex characters
pattern = r'\s*' + re.escape(character) + r'\s*'
return re.sub(pattern, f' {character} ', text)
# Test with different characters
test_text = "Hello-world|Python&Data#Science"
print("Original:", test_text)
print("With spaces around '-':", add_spaces_around_char(test_text, '-'))
print("With spaces around '|':", add_spaces_around_char(test_text, '|'))
print("With spaces around '&':", add_spaces_around_char(test_text, '&'))
Original: Hello-world|Python&Data#Science With spaces around '-': Hello - world|Python&Data#Science With spaces around '|': Hello-world | Python&Data#Science With spaces around '&': Hello-world|Python & Data#Science
Multiple Characters at Once
You can format multiple characters simultaneously using the pipe operator | in regex ?
import re
def format_multiple_chars(text, characters):
"""Add spaces around multiple characters."""
# Escape each character and join with |
escaped_chars = [re.escape(char) for char in characters]
pattern = r'\s*(' + '|'.join(escaped_chars) + r')\s*'
return re.sub(pattern, r' \1 ', text)
# Test string with multiple special characters
text = "Hello,world!How are-you?Great&amazing."
chars_to_format = [',', '!', '-', '?', '&']
formatted = format_multiple_chars(text, chars_to_format)
print("Original:", text)
print("Formatted:", formatted)
Original: Hello,world!How are-you?Great&amazing. Formatted: Hello , world ! How are - you ? Great & amazing.
Conclusion
Using regex with re.sub() makes it easy to add spaces around specific characters in Python. The pattern r'\s*character\s*' removes existing spaces and replaces them with properly formatted spacing. Use re.escape() for special regex characters to avoid unexpected behavior.
