- How to Remove Spaces from String in Python
- Howt to Remove White Spaces in Python String
- 1. str.strip()—Remove Leading and Trailing Spaces
- 2. str.replace()—Remove All White Spaces
- 3. str.join() and str.split()—Remove Duplicate White Spaces
- 4. str.translate()—Remove Tabs, Newlines, and Other White Spaces
- 5. re.sub()—Replace White Spaces with Empty Strings
- Conclusion
- Further Reading
- 3 thoughts on “How to Remove Spaces from String in Python”
- How To Remove Spaces from a String In Python
- Remove Leading and Trailing Spaces Using the strip() Method
- Remove All Spaces Using the replace() Method
- Remove Duplicate Spaces and Newline Characters Using the join() and split() Methods
- Remove All Spaces and Newline Characters Using the translate() Method
- Remove Whitespace Characters Using Regex
- Conclusion
How to Remove Spaces from String in Python
To remove spaces from a string in Python, use the str.replace() method.
This method takes two arguments:
- The first argument is the string to be replaced.
- The second argument is the string that replaces the string.
string = "This is a test" nospaces = string.replace(" ", "") print(nospaces)
To learn other useful string methods in Python, feel free to check this article.
In this guide, we take a look at other common situations related to removing spaces from a string.
Howt to Remove White Spaces in Python String
In Python, a string is an immutable type. This means it cannot be directly modified. This means any method that manipulates strings actually creates a new string.
In Python, there are many ways you can replace blank spaces:
Let’s go through each of these options and when you should use them.
1. str.strip()—Remove Leading and Trailing Spaces
The str.strip() method removes the leading and trailing whitespace from a string.
string = " This is a test " modified = string.strip() print(modified)
2. str.replace()—Remove All White Spaces
To wipe out all the white spaces from a string, you can use the str.replace() method.
This method takes two mandatory arguments:
- The target strings you want to get rid of.
- The string that replaces all the target strings.
In other words, to remove the white spaces, replace each white space with an empty string.
string = "This is a test" modified = string.replace(" ", "") print(modified)
3. str.join() and str.split()—Remove Duplicate White Spaces
To get rid of tabs, newlines, or any other duplicate whitespaces use str.join() method with str.split().
- The str.split() method splits the string into a list of words without spaces.
- The str.join() takes a list of words and joins them using the str as a separator.
For example, let’s remove the duplicate white spaces but leave single white spaces:
before = "This \t is a \n test \n\n \t let's modify this" after = " ".join(before.split()) print(before) print(after)
This is a test let's modify this This is a test let's modify this
4. str.translate()—Remove Tabs, Newlines, and Other White Spaces
To get rid of all the white spaces, tabs, newlines, you can use the str.translate() method with str.maketrans() method.
The str.translate() method replaces strings according to a translation table created by str.maketrans() method. In short, the str.maketrans() method works such that it takes three arguments:
- A string to be replaced.
- A string that specifies the characters to be replaced in the first argument.
- A list of characters to be removed from the original string. To remove white spaces, use string.whitespaces, which is a list of the types of blank spaces.
import string before = "This \t is a \n test \n\n \t let's modify this" after = before.translate(str.maketrans("", "", string.whitespace)) print(before) print(after)
Thisisatestlet'smodifythis
5. re.sub()—Replace White Spaces with Empty Strings
RegEx or Regular Expression is like a Ctrl+F on steroids.
You can use it to match patterns in a string. You can for example use regex to find phone numbers or email addresses from a text document.
I am not going to go into more details about regex, but here is a great article you can check.
To use Regular Expressions in Python to remove white spaces from a string:
- Import the regex module, re, to your project.
- Define a regex pattern that matches white spaces.
- Substitute each white space with a blank space using re.sub() method.
import re string = "This is a test" # Regular expression that matches each white space whitespace = r"\s+" # Replace all mathces with an empty string nospaces = re.sub(whitespace, "", string) print(nospaces)
Conclusion
Today you learned five ways to remove white spaces and duplicate white spaces from Python strings in different situations. Feel free to use the one that best fits your needs!
Thanks for reading. I hope you found an answer to your question.
Further Reading
3 thoughts on “How to Remove Spaces from String in Python”
Франчайзинговое соглашение – это, по сути,
юридическая документация между франчайзером
и вами (франчайзи). На самом деле не существует
основного типа франчайзи
При выборе яхты важно принять во чуткость чуть-чуть принципов.
Вначале, что поделаешь сделать свой выбор кот величиной яхты и еще обличьем движков, что придвинутся для
ваших потребностей. Во-других,
устремите внимание сверху бюджет, поскольку стоимость товаров сверху яхты смогут варьироваться через пары тыщ ут
пары миллионов долларов. Третьим принципом является поиск лично пригодной яхты.
Некоторые штаты могут принять яхту прямо у производителя, часть ну люд
покупать язык дилера или аукциона.
Сосредоточьте внимание, яко некоторые яхты смогут являться подвергнуты специальным лимитированиями и
еще запретам, так что перед покупкой вам стоит
расследовать наличность классических документов.
At the beginning, I was still puzzled. Since I read your article, I have been very impressed. It has provided a lot of innovative ideas for my thesis related to gate.io. Thank u. But I still have some doubts, can you help me? Thanks.
How To Remove Spaces from a String In Python
This tutorial provides examples of various methods you can use to remove whitespace from a string in Python.
A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.
The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove spaces. The examples use the following string:
s = ' Hello World From DigitalOcean \t\n\r\tHi There '
Output Hello World From DigitalOcean Hi There
This string has different types of whitespace and newline characters, such as space ( ), tab ( \t ), newline ( \n ), and carriage return ( \r ).
Remove Leading and Trailing Spaces Using the strip() Method
The Python String strip() method removes leading and trailing characters from a string. The default character to remove is space.
Declare the string variable:
Use the strip() method to remove the leading and trailing whitespace:
Output'Hello World From DigitalOcean \t\n\r\tHi There'
If you want to remove only the leading spaces or trailing spaces, then you can use the lstrip() and rstrip() methods.
Remove All Spaces Using the replace() Method
You can use the replace() method to remove all the whitespace characters from the string, including from between words.
Declare the string variable:
Use the replace() method to replace spaces with an empty string:
Output'HelloWorldFromDigitalOcean\t\n\r\tHiThere'
Remove Duplicate Spaces and Newline Characters Using the join() and split() Methods
You can remove all of the duplicate whitespace and newline characters by using the join() method with the split() method. In this example, the split() method breaks up the string into a list, using the default separator of any whitespace character. Then, the join() method joins the list back into one string with a single space ( » » ) between each word.
Declare the string variable:
Use the join() and split() methods together to remove duplicate spaces and newline characters:
Output'Hello World From DigitalOcean Hi There'
Remove All Spaces and Newline Characters Using the translate() Method
You can remove all of the whitespace and newline characters using the translate() method. The translate() method replaces specified characters with characters defined in a dictionary or mapping table. The following example uses a custom dictionary with the string.whitespace string constant, which contains all the whitespace characters. The custom dictionary replaces all the characters in string.whitespace with None .
Import the string module so that you can use string.whitespace :
Declare the string variable:
Use the translate() method to remove all whitespace characters:
Output'HelloWorldFromDigitalOceanHiThere'
Remove Whitespace Characters Using Regex
You can also use a regular expression to match whitespace characters and remove them using the re.sub() function.
This example uses the following file, regexspaces.py , to show some ways you can use regex to remove whitespace characters:
import re s = ' Hello World From DigitalOcean \t\n\r\tHi There ' print('Remove all spaces using regex:\n', re.sub(r"\s+", "", s), sep='') # \s matches all white spaces print('Remove leading spaces using regex:\n', re.sub(r"^\s+", "", s), sep='') # ^ matches start print('Remove trailing spaces using regex:\n', re.sub(r"\s+$", "", s), sep='') # $ matches end print('Remove leading and trailing spaces using regex:\n', re.sub(r"^\s+|\s+$", "", s), sep='') # | for OR condition
Run the file from the command line:
You get the following output:
Remove all spaces using regex: HelloWorldFromDigitalOceanHiThere Remove leading spaces using regex: Hello World From DigitalOcean Hi There Remove trailing spaces using regex: Hello World From DigitalOcean Hi There Remove leading and trailing spaces using regex: Hello World From DigitalOcean Hi There
Conclusion
In this tutorial, you learned some of the methods you can use to remove whitespace characters from strings in Python. Continue your learning about Python strings.
Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!