In this tutorial, I am going to remove all spaces from a string using different methods. It involves removing any whitespace present in the string. In Python string is Immutable, so when you use any method to manipulate string it will return as a new string.
Method 1
Using .replace()
In this code, we will be using the .replace() function to remove any whitespace present in the string. The .replace() takes three parameters old value, new value, and count. The count is optional it specifies how many values you want to replace.
Code:
str = "The One Piece is Real" result = "" #Removing spaces from the string result = str.replace(" ", "") print(result)
Output:
TheOnePieceisReal
Method 2
Using .split()
In this code, we will be using the .split() function to remove whitespaces from a string. The split() function splits a string and stores it into a list. The default separator is whitespace but you can specify the separator according to your need.
Code:
str = "The One Piece is Real" result = "" #Removing spaces from the string words = str.split() for i in words: result = result + i print(result)
Output:
TheOnePieceisReal