How to remove spaces from both ends of string in Python
In Python, you can remove spaces from both ends of a string using the string.replace function. This function takes two arguments: the string to be ...

In Python, you can remove spaces from both ends of a string using the string.replace() function. This function takes two arguments: the string to be replaced and a replacement string. The replacement string is a string that will be used to replace all the spaces in the original string.
To remove spaces from both ends of a string in Python, you can use the following code:
string.replace("hello", "ello", "")
This code will replace all the spaces in the string "hello" with the string "ello".
- In Python, how do you remove all spaces from a string?
- How to Use Python to Remove All Whitespaces from a String
- In Python, how do you remove spaces from the beginning of a string?
- Get Rid of Trailing Spaces in a Python String
- In Python, remove spaces from the beginning and end of a string.
- How to Use Python to Remove Extra Spaces Between Words in a String
- How to Remove Spaces from a String Using Python Regular Expressions
- Replace Spaces at the Beginning of a String with a Regular Expression
- How to Replace Spaces at the End of a String with a Regular Expression
- Related posts:
- Which method removes whitespace from the beginning and end of a string?
- How do I remove spaces from the beginning and end of a Python string?
- How do you get rid of the space at the end of a string?
- In Python, how do you remove two consecutive spaces?
string replaceinString(std::string str, std::string tofind, std::string toreplace)
{
size_t position = 0;
for ( position = str.find(tofind); position != std::string::npos; position = str.find(tofind,position) )
{
str.replace(position ,1, toreplace);
}
return(str);
}
use it:
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
If you're wondering how to remove spaces from a string in Python, you've come to the right place. Keep reading to learn how to do it quickly.
There are several methods for removing spaces from a Python string. The string replace() method is the most basic approach. If the spaces to be removed are only at the beginning and end of the string, the strip() method will also work. Another option is to use a regular expression.
We will begin with the approach that works in the majority of cases and then consider other options to provide you with a more comprehensive understanding of the subject.
We're coming for you, Spaces!
In Python, how do you remove all spaces from a string?
The Python string replace() method is the simplest way to remove all spaces from a string.
Let's try it with the string below.:
>>> message = " Welcome to Codefather.tech "
>>> print(message.replace(" ",""))
WelcometoCodefather.tech
The replace() method replaces occurrences of the substring passed as the first argument (in this case, a space " ") with the second argument (in this case, an empty character " ").
It also accepts an optional third argument that specifies how many occurrences of the first substring (in this case, the space) should be replaced.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
The first and second spaces, as seen, have been replaced with an empty character, but the third space has not been replaced.
Quite handy!
Note: Given that Python strings are immutable, the replace method returns a copy of the original string.
What if you want to use underscores instead of whitespaces?
The following command can be used to replace whitespaces in a Python string with underscores.:
>>> message.replace(" ","_")
'_Welcome_to_Codefather.tech_'
How to Use Python to Remove All Whitespaces from a String
The split() and join() functions can also be used to remove whitespaces from a string.
First, we split our string using the split() function.:
>>> message.split()
['Welcome', 'to', 'Codefather.tech']
Interesting…
..the split() method converts our string into a list of strings, removing all whitespace.
This means we can use the string join() method to join the items in the list.
The syntax for the join() method is as follows::
"{string_to_be_used_as_separator}".join(iterable)
And here's how you can apply it to an empty string in practice.
>>> "".join(message.split())
'WelcometoCodefather.tech'
Nice!
You can use the following instead if you want to keep the spaces between the three words..
>>> message = " Welcome to Codefather.tech "
>>> " ".join(message.split())
'Welcome to Codefather.tech'
In Python, how do you remove spaces from the beginning of a string?
What if you only want to get rid of spaces at the start of a string?
Assume we have the following string..
>>> message = " Hello"
The string lstrip() method can be used to remove leading spaces.
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
0There will be no trailing spaces after using this method.
Get Rid of Trailing Spaces in a Python String
Python's rstrip() string method can be used to remove trailing spaces from a string.
string replace = replaceinString(thisstring, " ", "%20");
string replace2 = replaceinString(thisstring, " ", "-");
string replace3 = replaceinString(thisstring, " ", "+");
1The leading spaces have not been removed, as we can see. However, because we can't see them, it's difficult to confirm that the trailing spaces have been removed.
Let's try something to make sure they're gone.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
0We can confirm that three characters (the trailing spaces) have been removed from the string by using the len() function.
In Python, remove spaces from the beginning and end of a string.
We saw in the previous two sections that Python has two string methods for removing spaces from the beginning and end of a string.
What if we want to remove spaces from both the beginning and end of a string using a single line of code?
The string strip() method can be used to remove spaces from the beginning and end of a string.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
1The strip() method returns a string with only 5 characters because spaces at the beginning and end of the string have been removed.
In theory, you could achieve the same result by combining the lstrip() and rstrip() methods in a single line of code.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
2Using the dot notation, Python allows the application of two methods in a single line of code.
You now understand how to remove spaces from the beginning and end of a string.
How to Use Python to Remove Extra Spaces Between Words in a String
There may be times when you do not want to replace all of the spaces in a string, but simply remove some extra spaces.
Assume you want to replace two consecutive spaces (where they exist) with a single space.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
3There are two spaces between the three words, which I want to replace with one. To accomplish this, we can employ the replace() method.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
4As the first argument, we pass two consecutive spaces (" ") and a single space (" ") as the second argument.
How to Remove Spaces from a String Using Python Regular Expressions
Let's look at another method for removing spaces from a string.: Python regular expressions will be used.
Regular expressions are one of the topics that many developers avoid, particularly at the start of their coding career.
But…
..regular expressions are extremely powerful, and it is a good practice to use them frequently in order to become accustomed to them.
Python's regular expression handling module is known as re. We will use the re to remove spaces from a Python string.sub() function.
The syntax of the re is as follows:.sub() function:
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
5>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
6Is the NameError exception visible above?
It is due to the fact that we did not first import the re module.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
7Let's look at the pattern to be replaced since the other two arguments are fairly simple.
What does “\s+” mean?
A Python regular expression pattern matches whitespace characters (including [. When the lowercase s is replaced with a capital s ("S "), the pattern matches any non-whitespace character.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
8Makes sense?
Replace Spaces at the Beginning of a String with a Regular Expression
A regular expression can also be used to replace spaces at the start of a string by adding an extra character to the previous pattern.
>>> print(message.replace(" ","", 2))
Welcometo Codefather.tech
9To refer to the beginning of the line, we added the character at the beginning of the pattern.
The outcome is the same as with the lstrip() method.
>>> message.replace(" ","_")
'_Welcome_to_Codefather.tech_'
0How to Replace Spaces at the End of a String with a Regular Expression
To remove trailing spaces from a string, we can use regular expressions instead of the rstrip() method.
Let's see what else we can add to the regular expression pattern to get it to work.
>>> message.replace(" ","_")
'_Welcome_to_Codefather.tech_'
1By appending the $ symbol to the end of the "s" pattern, you can match only the whitespaces at the end of the string.
The outcome is the same as with the rstrip() method..
>>> message.replace(" ","_")
'_Welcome_to_Codefather.tech_'
2Conclusion
There are now numerous methods for replacing or removing white spaces from Python strings.
Simply choose the one that appeals to you and is also appropriate for the situation at hand.
Bonus read: You learned how to remove spaces from strings in Python in this tutorial. Take a look at to supplement your knowledge. It will be beneficial to your Python programs!
Related course: construct a solid Python foundation with.
Related posts:
8 Python Tips for Counting Unique Values in a List
How to Determine Whether a Python String Has a Number
What is __name__ in Flask: Let's Learn Python Together
Claudio Sabato
I work as a Technical Lead, Software Engineer, and Programming Coach. I'd like to assist you in your quest to become a Super Developer!