views:

15660

answers:

3

I need to write a function in python that gets a string-

If the first or last characters in the string are spaces, then they should be removed (both). If not than nothing should be done.

" Hello " ----> "Hello"

" Hello" -----> "Hello"

"Hello " -----> "Hello"

"Bob has a cat" ----> "Bob has a cat" (none of the spaces in the middle are removed.)

+7  A: 
myString.strip()
Deniz Dogan
+2  A: 

You want strip():

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

for phrase in myphrases:
    print phrase.strip()
vezult
+39  A: 

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

>>> ' Hello '.strip()
'Hello'
>>> ' Hello'.strip()
'Hello'
>>> 'Bob has a cat'.strip()
'Bob has a cat'
>>> '          Hello        '.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("   Hello ")
'  Hello'

Also, note that str.strip() removes other whitespace characters as well (eg. tabs and newlines). To remove only spaces, you can specify the character to remove as an argument to strip. ie:

>>> "  Hello\n".strip(" ")
'Hello\n'
Brian