Python program to remove spaces from string
#Python #program #remove_spaces from string
This tutorial provides examples of various methods you can use to remove whitespace from a string in Python.
A Python String is immutable, so you can’t change its value. Any method that manipulates a string value returns a new string.
Example 1: This is example without inbuilt method :
# input from the user
string = input(“Enter a String : “)
result=''
#loop the string
for i in string:
#if the character is not a space
if i!=' ':
result += i
print("String after removing the spaces :",result)
Example 2: This is example with inbuilt method
# Define a function 'remove_myspaces' that takes a string 'str1' as input.
def remove_myspaces(str1):
#python program to remove spaces from string without inbuilt function
how to remove space in python output
# Use the 'replace' method to remove spaces (' ') in the input string 'str1'.
str1 = str1.replace(' ', '')
return str1 # Return the modified string without spaces.
# Call the 'remove_myspaces' function with different input strings and print the results.
print(remove_spaces("w 3 res ou r ce"))
print(remove_spaces("a b c"))
In this Article , we used in built method like replace to replace space.
The Python String strip() method removes leading and trailing characters from a string. The default character to remove is space.