How to remove spaces from strings in Python

Source: Internet
Author: User

We often encounter many space-related issues when processing strings. Manually deleting strings one by one is not what our programmers should do. Let's talk about this article, how to Use Python to remove spaces in strings.
First, create a string variable s with around N spaces. See the Code:
Copy codeThe Code is as follows: >>> s = ""
>>>
Remove string spaces. There is a built-in method in Python. We don't need to build the wheel on our own.
Lstrip: removes spaces on the left.
This string method deletes spaces before the start position of string s.
Copy codeThe Code is as follows: >>> s. lstrip ()
'Foot home'
Rstrip: Delete the right-connected Space
This built-in method can delete all spaces at the end of a string. See the following DEMO code:
Copy codeThe Code is as follows: >>> s. rstrip ()
'Foot home'
Strip: removes spaces at both ends.
Sometimes, when we read the content in the file, there are spaces on both sides of each line. Can we remove them all at once? The character has a built-in strip () method.
Copy codeThe Code is as follows: >>> s = ""
>>> S. strip ()
'Foot home'
Tip: You can use the dir (str) method to obtain the list of all methods of the str string.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.