π Day 67/150 – Remove Spaces from String in Python
Sometimes while working with strings, we need to remove spaces from text data.
Example:
"Python Programming" → "PythonProgramming"
Python provides multiple easy ways to do this. Let’s explore them π
πΉ Method 1 – Using replace()
text = "Python Programming"
PythonProgrammingresult = text.replace(" ", "") print(result)
✅ Output
π replace() replaces all spaces with an empty string.
πΉ Method 2 – Taking User Input
text = input("Enter a string: ") result = text.replace(" ", "") print("After Removing Spaces:", result)
✅ Example Output
Enter a string: Python ProgrammingAfter Removing Spaces: PythonProgramming
π Useful when working with user-entered text.
πΉ Method 3 – Using split() and join()
PythonProgrammingtext = "Python Programming" result = "".join(text.split()) print(result)
✅ Output
π split() separates words and join() combines them without spaces.
πΉ Method 4 – Using for Loop
PythonProgramming
✅ Output
π This method manually checks each character and skips spaces.
π₯ Key Takeaways
✅ replace() is the easiest method
✅ split() + join() is clean and efficient
✅ Loops help understand string manipulation logic
✅ Removing spaces is useful in text cleaning tasks


0 Comments:
Post a Comment