Skip to content

Latest commit

 

History

History
65 lines (36 loc) · 2.56 KB

Python_Remove_all_spaces_on_string.md

File metadata and controls

65 lines (36 loc) · 2.56 KB



Template request | Bug report | Generate Data Product

Tags: #python #remove #string #space

Author: Benjamin Filly

Description: This notebook shows how to remove all spaces from a string using two different methods

References:

Input

Setup Variables

  • string: character string space you want to remove
string = "Hello, world! This is a string with spaces."

Model

Method 1 : Delete all space using replace

In this example, the replace() method is called on the string variable. It takes two arguments: the substring to be replaced (" ") and the new substring to replace it with ("").

Note that the replace()method returns a new string with the replacements made, while the original string remains unchanged.

string_without_spaces1 = string.replace(" ", "")
string_without_spaces1

Method 2: Using join and split method

  • string.split() : Thesplit()method is called on the stringvariable without any arguments. It divides the string into a list of substrings, using space characters (spaces, tabs or line breaks) as delimiters.
  • "".join : The join() method is called on an empty string "" and takes the result of string.split() as argument. It concatenates the substrings of the list together, using the empty string as separator.
string_without_spaces2 = "".join(string.split())
string_without_spaces2

Output

Display result 1

print("String without spaces:", string_without_spaces1)

Display result 2

print("String without spaces:", string_without_spaces2)