Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Understanding Character Encoding
Next article icon

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:

Using replace() method

To remove all spaces from a string, we can usereplace()method.

Python
s="Python is fun"s=s.replace(" ","")print(s)

Output
Pythonisfun

Explanation: s.replace(" ", "") replaces every space ins with an empty string "", effectively removing them.

Removing Leading and Trailing Spaces

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.

Python
s="   Hello World   "s=s.strip()print(s)

Output
Hello World

Explanation:s.strip() removes spaces from the start and end ofs.

Removing Leading Spaces Only

If we only want to remove spaces from the beginning of the string, we can uselstrip().

Python
s="   Hello World"s=s.lstrip()print(s)

Output
Hello World

Explanation:s.lstrip() removes spaces from the left side ofs only.

Removing Trailing Spaces Only

Similarly, to remove spaces from the end of a string, we can userstrip().

Python
s="Hello World   "s=s.rstrip()print(s)

Output
Hello World

Explanation:s.rstrip() removes spaces from the right side ofs only.

Related Articles:


Python program to remove spaces from a string
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp