![]() |
VOOZH | about |
Removing spaces from a string is a common task in Python that can be solved in multiple ways. For example, if we have a string like " g f g ", we might want the output to be "gfg" by removing all the spaces. Let's look at different methods to do so:
To remove all spaces from a string, we can use replace() method.
Pythonisfun
Explanation: s.replace(" ", "") replaces every space in s with an empty string "", effectively removing them.
Sometimes, we only need to remove spaces from the start and end of a string while leaving the inner spaces untouched. In such cases, strip() method is ideal.
Hello World
Explanation:s.strip() removes spaces from the start and end of s.
If we only want to remove spaces from the beginning of the string, we can use lstrip().
Hello World
Explanation:s.lstrip() removes spaces from the left side of s only.
Similarly, to remove spaces from the end of a string, we can use rstrip().
Hello World
Explanation:s.rstrip() removes spaces from the right side of s only.
Related Articles: