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 remove tabs and newlines using Python regular expression?
Regular expressions provide a powerful way to remove tabs and newlines from strings. Python's re.sub() function can replace whitespace characters including tabs (\t) and newlines (\n) with spaces or remove them entirely.
Basic Approach Using \s+
The \s+ pattern matches one or more whitespace characters (spaces, tabs, newlines) and replaces them with a single space ?
import re text = """I find Tutorialspoint helpful""" result = re.sub(r"\s+", " ", text) print(result)
I find Tutorialspoint helpful
Removing Only Tabs and Newlines
To target only tabs and newlines while preserving regular spaces, use the pattern [\t\n]+ ?
import re text = """Python is great for data science""" # Remove only tabs and newlines result = re.sub(r"[\t\n]+", " ", text) print(result)
Python is great for data science
Complete Removal Without Replacement
To completely remove tabs and newlines without adding spaces, use an empty string as replacement ?
import re text = """Hello World Tab""" # Remove completely without spaces result = re.sub(r"[\t\n]", "", text) print(result)
HelloWorldTab
Comparison of Methods
| Pattern | Matches | Best For |
|---|---|---|
\s+ |
All whitespace (spaces, tabs, newlines) | General whitespace cleanup |
[\t\n]+ |
Only tabs and newlines | Preserving regular spaces |
[\t\n] |
Individual tabs and newlines | Complete removal |
Conclusion
Use re.sub(r"\s+", " ", text) to normalize all whitespace to single spaces. For targeted removal of only tabs and newlines, use [\t\n]+ pattern to preserve existing spaces in your text.
