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:
string
: character string space you want to remove
string = "Hello, world! This is a string with spaces."
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
string.split()
: Thesplit()
method is called on thestring
variable without any arguments. It divides the string into a list of substrings, using space characters (spaces, tabs or line breaks) as delimiters."".join
: Thejoin()
method is called on an empty string""
and takes the result ofstring.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
print("String without spaces:", string_without_spaces1)
print("String without spaces:", string_without_spaces2)