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 ...

Emily Blunt
Emily Blunt
5 min read
Days of Wine and Roses with James Comey

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".

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, " ", "+");
0

There 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, " ", "+");
1

The 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  
0

We 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  
1

The 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  
2

Using 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  
3

There 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  
4

As 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  
6

Is 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  
7

Let'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  
8

Makes 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  
9

To 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_' 
0

How 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_' 
1

By 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_' 
2

Conclusion

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.

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!

Which method removes whitespace from the beginning and end of a string?

trim() Trim() removes whitespace from both ends of a string and returns a new string without changing the original string. TrimStart() and trimEnd() are functions that return a new string with whitespace trimmed from only one end. .

How do I remove spaces from the beginning and end of a Python string?

Use the . strip() method to remove whitespace and characters at the start and end of a string. Use the . To remove whitespace and characters only from the beginning of a string, use the lstrip() method.

How do you get rid of the space at the end of a string?

The String. trim() method # You can call the trim() method on your string to remove whitespace from the beginning and end of it. It returns a new string.

In Python, how do you remove two consecutive spaces?

How to Remove Consecutive Spaces in a String in Python 3 .
Pythonic code with split and join operations. out = " ".join(my_str.split()).
using a regular expression. out1 = re.out = re sub("ss ", ", my_str).sub(' +', ' ', my_str).

remove spaces ends string python

Emily Blunt Twitter

Hi, my name is Emily Blunt and I am a 5-year experienced blogger in the field of pet care.


Related Post

Public

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 replaced and a replacement string. The replacement

How to remove spaces from both ends of string in Python
Public

How to Remove the Last Two Characters from a String in Python

In Python, strings can be shortened by removing the last two characters. This is done by using the string slice operator, which takes two arguments: the start and end position of the slice.For example

How to Remove the Last Two Characters from a String in Python
Public

How to Reverse a String in Python Using a for Loop

In Python, you can reverse a string using a for loop. The syntax is as follows:string_to_reverse = "string to reverse"for i in range(0, len(string_to_reverse)):string_to_reverse[i], string_to_reverse[

How to Reverse a String in Python Using a for Loop
Public

1. Create a list of empty lists in Python.2. Create a list of empty lists in Python with different data types.3. Create a list of empty lists in Python with different methods.4. Create a list of empty lists in Python with different functions.5. Create a list of empty lists in Python with different operators.

If you want to learn how to efficiently create an empty list in Python, this article is for you.You will learn:Using square brackets to make an empty list >>> num = [] >>> len(num) 0

1. Create a list of empty lists in Python.2. Create a list of empty lists in Python with different data types.3. Create a list of empty lists in Python with different methods.4. Create a list of empty lists in Python with different functions.5. Create a list of empty lists in Python with different operators.
Public

Can you use Python in Visual Studio on Mac?

Python is a powerful programming language that can be used in a variety of applications, including software development. Python can be used in Visual Studio on Mac, but there are a few considerations

Can you use Python in Visual Studio on Mac?
Public

How to get email address from facebook

There are a few ways to get email addresses from Facebook. The easiest way is to use Facebook's "Find Friends" feature. You can enter the name of a person you know and Facebook will return all of that

How to get email address from facebook
Public

How to access icloud from my iphone

If you have an iPhone, you can access your iCloud account from your iPhone. To do this, open the Settings app on your iPhone and scroll down to iCloud. Tap on iCloud and sign in to your account. You c

How to access icloud from my iphone
Public

How to write a Python for loop to write data to a CSV file?

A for loop is a programming construct that allows you to repeat a set of instructions a set number of times. In Python, a for loop looks like this:for i in range(1, 10):This for loop will execute the

How to write a Python for loop to write data to a CSV file?
Public

How do I get the parent object from a child object in Laravel?

If you want to get the parent object from a child object in Laravel, you can use the parent() method. This method will return the parent object of the given child object.For working with your database

How do I get the parent object from a child object in Laravel?
Public

Can I take a shuttle from my VPS in San Diego to Miramar Beach?

If you are looking to take a shuttle from your VPS in San Diego to Miramar Beach, the best option may be to use a shuttle service like Beach Shuttle. This company offers a variety of shuttle options t

Can I take a shuttle from my VPS in San Diego to Miramar Beach?