Skip to content
  • YouTube
  • FaceBook
  • Twitter
  • Instagram

Data Analytics Ireland

Data Analytics and Video Tutorials

  • Home
  • Contact
  • About Us
    • Latest
    • Write for us
    • Learn more information about our website
  • Useful Links
  • Glossary
  • All Categories
  • Faq
  • Livestream
  • Toggle search form
  • data cleansing in a business environment Articles
  • How To Pass Data Between Functions Python Functions
  • how to reverse a string in python strings
  • How to pass multiple lists to a function and compare Python Functions
  • How to Automate Testing With Python | unittest automation
  • How to count the no of rows and columns in a CSV file CSV
  • IndexError: single positional indexer is out-of-bounds Index Error
  • TypeError: ‘list’ object is not an iterator Python

how to remove spaces from a string

Posted on January 28, 2021February 9, 2021 By admin No Comments on how to remove spaces from a string

Have you encountered a problem where you have some spaces in a string that you do not need?

Data analytics can throw up lots of challenges we hope to help you solve this problem easily.

This problem can be quite common and can cause problems as follows:

  • Comparing strings does not work as expected.
  • Automated processes may fail as the presence of a space may make it fall over.

So lets look at some common ways to find these problems and then fix them.

Removing spaces at the start or end of the file using strip()

A common way to achieve this , will remove white spaces at the start and send of your string, BUT not in the middle.

This would be very helpful where you want to format some strings before loading them into a database, as the white spaces can cause the load to fail.

spacedstring = " Please remove my spaces! "
print("Before",spacedstring)
print("After",spacedstring.strip())

Output:
Before:  Please remove my spaces! 
After: Please remove my spaces!

Removing all spaces using str.replace()

Quite simply this removes all the white spaces in the string, resulting in all the characters form one long string.

The first part of the function looks to identify empty spaces, then the second part looks to remove it.

spacedstring = " Please remove my spaces! "
print(spacedstring.replace(" ", ""))

Output = Pleaseremovemyspaces!

Remove spaces using a regular expression

A regular expression is widely used across a number of languages , as a result is a very powerful way to search for pattern matching.

It looks to create a combination of characters that the computer programme understands and applies to a string.

The re.compile() method saves the regular expression for re use, which is know to be more efficient.

With re.sub() , it takes the string spacedstring, looks for “pattern” in it and removes it and replaces it with “”, which basically is nothing.

import re
spacedstring = " Please remove my spaces! "
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', spacedstring)
print(sentence)

Output = Pleaseremovemyspaces!

Using the join and split function together

Using the below code has two steps:

(A)The split function() first of all splits all the words in a string into a list. By doing this it removes any spaces in the original string.

(B) the .join then pulls them all back together.

(C) Finally as you have “” at the start, it tells the program not to include any spaces between the words.

spacedstring = " Please remove my spaces! "
print("".join(spacedstring.split()))

Output = Pleaseremovemyspaces!

So there you have a number of different ways to remove spaces inside a string.

One final things to note about regular expressions covered above:

  • They are generally quite short in nature, less code needs to be written to implement.
  • When they were written, the performance was front and centre, as a result, they are very quick.
  • They work over a number of different languages, so no changes need to made.

regular expressions, strings Tags:pattern matching, regex, remove spaces, remove spaces from string, split function

Post navigation

Previous Post: how do I merge two dictionaries in Python?
Next Post: how do I declare a null value in python?

Related Posts

  • how to reverse a string in python strings
  • How to use wildcards in SQL SQL
  • How To Check For Unwanted Characters Using Loops With Python Python Data Cleansing
  • TypeError: type object is not subscriptable strings
  • Regular expressions python Python
  • ValueError: Columns must be same length as key exception handling

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Select your language!

  • हिंदी
  • Español
  • Português
  • Français
  • Italiano
  • What does a data analyst do? Livestream
  • Tkinter GUI tutorial python – how to clean excel data Python
  • how to write subqueries in SQL SQL
  • How to Add Formulas to Excel using Python numpy
  • planning your machine learning model machine learning
  • YouTube channel lists – Tuples Python Tuples
  • Welcome to Data Analytics Ireland Livestream
  • R tutorial – How to sort lists using rstudio R Programming

Copyright © 2023 Data Analytics Ireland.

Powered by PressBook Premium theme

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Cookie settingsACCEPT
Privacy & Cookies Policy

Privacy Overview

This website uses cookies to improve your experience while you navigate through the website. Out of these cookies, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may have an effect on your browsing experience.
Necessary
Always Enabled
Necessary cookies are absolutely essential for the website to function properly. This category only includes cookies that ensures basic functionalities and security features of the website. These cookies do not store any personal information.
Non-necessary
Any cookies that may not be particularly necessary for the website to function and is used specifically to collect user personal data via analytics, ads, other embedded contents are termed as non-necessary cookies. It is mandatory to procure user consent prior to running these cookies on your website.
SAVE & ACCEPT