1

I want to make a function that strips whitespace from a string, what I have so far is:

def stripped(x):
    x = x.replace('  ', '')

string = " yes   Maybe   So"

I want to just strip the space by doing this

string.stripped()

but I keep getting this error AttributeError: 'str' object has no attribute 'stripped'

what am I doing wrong I am guessing it is something simple I am just overlooking, thanks in advance.

Cannon
  • 309
  • 4
  • 19

3 Answers3

1

When you define your function, you Python creates a lone function object called stripped. It doesn't add your function to the builtin str object. You just

need to call your method on the string normally:

>>> def stripped(x):
    x = x.replace('  ', '')


>>> string = " yes   Maybe   So"
>>> stripped(string)
>>> 

Note however string will not be modified, You need to return the result of x.replace() and assign it to string:

>>> def stripped(x):
    return x.replace('  ', '')

>>> string = " yes   Maybe   So"
>>> string = stripped(string)
>>> string
' yes Maybe So'
>>>

Note what your asking for is techinally possible. It is a monkey-patch however and shouldn't be used. But just for completeness:

>>> _str = str
>>> 
>>> class str(_str):
    def stripped(self):
        return self.replace('  ', '')


>>> string = str(" yes   Maybe   So")
>>> string.stripped()
' yes Maybe So'
>>>
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

You can't add a method to an existing class like that. You could write a function that receives and returns a string:

def stripped(x):
    return x.replace('  ', '')

And the call it by passing your string:

s = " yes   Maybe   So"
s = stripped(s)
Mureinik
  • 297,002
  • 52
  • 306
  • 350
-1

If you want all whitespace, not just spaces, you can do ''.join(string.split())

def stripped(string):
    return ''.join(string.split())

string = stripped(' yes   Maybe   So')

# But it would also handle this
string = stripped(' yes \n Maybe  So\n')
assert string == 'yesMaybeSo'
Brett Beatty
  • 5,690
  • 1
  • 23
  • 37
  • While this does perhaps offer a better method, it doesn't answer the main question, which is probably why you got downvoted. (I didn't downvote). – Christian Dean Jun 22 '17 at 17:47