how python trim works

+1 vote

How to remove whitespaces from a string?

Apr 15, 2018 in Python by ana1504.k
• 7,870 points
133 views

6 answers to this question.

0 votes

It depends on one such space or all spaces. If the second, then strings already have a .strip() method:

>>> ' Welcome '.strip()
'Welcome'
>>> ' Welcome'.strip()
'Welcome'

>>> ' Welcome '.strip() # ALL spaces at ends removed
'Hello'

If you need only to remove one space however, you could do it with:

def strip_one_space(s):
if s.endswith(" "): s = s[:-1]
if s.startswith(" "): s = s[1:]
return s

>>> strip_one_space(" Welcome ")
' Hello'
Also, note that str.strip() removes other whitespace characters as well (e.g. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip, i.e.:

>>> " Welcome\n".strip(" ")
'Welcome\n'

answered Apr 15, 2018 by anto.trigg4
• 3,420 points
+1 vote
>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
answered Oct 18, 2018 by kalgie Mathew
+1 vote

If you need only to remove one space however, you could do it with:

def strip_one_space(s):
    if s.endswith(" "): s = s[:-1]
    if s.startswith(" "): s = s[1:]
    return s

>>> strip_one_space("   Hello ")
'  Hello'
answered Oct 18, 2018 by neha basuriwala
+1 vote

strip is not limited to whitespace characters either:

# remove all leading/trailing commas, periods and hyphens
title = title.strip(',.-')
answered Oct 18, 2018 by zulekha frm edureka
+1 vote

You want strip():

myphrases = [ " Hello ", " Hello", "Hello ", "Bob has a cat" ]

for phrase in myphrases:
    print phrase.strip()
answered Oct 18, 2018 by up4rescue
0 votes
You can use .strip() function to trim the whitespace from your text.
answered Feb 14 by Shashank
• 1,350 points

Related Questions In Python

0 votes
1 answer
0 votes
1 answer

How do I trim extra zeros from a 2D array in python?

Hey @Laksha, you can try something like ...READ MORE

answered May 29 in Python by Yamini
36 views
0 votes
0 answers

how does sorted function works in python?

How are the arguments passed in the ...READ MORE

Jul 19 in Python by Waseem
• 4,470 points
29 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,810 points
202 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 345 views
+4 votes
6 answers
+2 votes
6 answers

How can I change directory or "cd" in Python?

Context Manager: cd import os class cd:     """Context manager for ...READ MORE

answered Oct 18, 2018 in Python by Nabarupa
136 views
+2 votes
6 answers

Slicing in Python

Index: ------------> ...READ MORE

answered Oct 18, 2018 in Python by abc
127 views