Python program to remove spaces from string
#Python strip() method for trimming leading and trailing spaces #Python #program #remove_spaces from string
This tutorial provides examples of various methods you can use to remove whitespace from a string in Python.
Removing spaces from strings in Python is a common task, especially when cleaning data or formatting text for output. In this tutorial, we will explore multiple methods to remove spaces from a string in Python, including both manual and built-in approaches.
By the end of this guide, you will learn:
✅ How to remove spaces from a string using a loop.
✅ How to use Python's built-in methods like replace()
and strip()
.
✅ Best practices for handling whitespace in Python.
You can manually remove spaces by looping through the string and building a new one without spaces.
# Input from the user
string = input("Enter a String: ")
result = ''
# Loop through the string
for i in string:
if i != ' ': # If the character is not a space, add it to result
result += i
print("String after removing spaces:", result)
result
.replace()
Method
Python provides a built-in method, replace()
, to remove spaces efficiently.
# Define a function to remove spaces
def remove_spaces(str1):
return str1.replace(' ', '') # Replace all spaces with an empty string
# Test cases
print(remove_spaces("w 3 res ou r ce"))
print(remove_spaces("a b c"))
replace(' ', '')
function replaces all spaces in the string with an empty string.join()
string = "Python is fun!"
result = "".join([char for char in string if char != ' '])
print(result) # Output: Pythonisfun!
strip()
to Remove Leading and Trailing Spacesstring = " Hello, World! "
print(string.strip()) # Output: "Hello, World!"
In this guide, we explored multiple ways to remove spaces from a string in Python:
replace()
method for quick and efficient space removal.join()
for a concise approach.strip()
method for leading and trailing space removal.These techniques are essential for data cleaning, text processing, and formatting output in Python. 🚀 Try them out in your Python programs!