Welcome!
This is the community forum for my apps Pythonista and Editorial.
For individual support questions, you can also send an email. If you have a very short question or just want to say hello — I'm @olemoritz on Twitter.
Function at end of variable (Don't really know how to sum up this question)
-
Hi,
so I have this function:def clean(data): while data.startswith(' '): data = data[1:] while data.endswith(' '): data = data[:-1] return data
Therefore clean(" random string ") returns "random string" . Is it possible to get the same result with " random string ".clean() ?
After all "random string".lower() is possible too. -
@Drizzel is that not the strip function?
-
@cvp True, forgot about that :)
Nevertheless, is it possible to do this in general? -
-
You can subclass str and insert your method in the subclass definition. As long as you use your subclass to create your “string” instances the new method would work. Not for literals though. E.g.,
class funny_string(str): def clean(data): while data.startswith(' '): data = data[1:] while data.endswith(' '): data = data[:-1] return data my_string = funny_string(“ look at this! “) print(my_string.clean()) #### works print(“ huh? “.clean()) #### doesn’t work
-
@Drizzel, well, sort of, see below. But not really, since you cannot modify the built-in class (
str.a = 'a'
results in an error).from collections import UserString class Cleanable(UserString): def clean(self): return self.strip() mystr = Cleanable(' random string ') assert 'string' in mystr assert mystr.clean() == 'random string'
-
-
@Drizzel said:
def clean(data):
while data.startswith(' '): data = data[1:]
while data.endswith(' '): data = data[:-1]
return dataJust for fun, a couple comments on this function. As written I think it's going to be safe in all cases, but a subtle point is that if the passed in object starts or ends with a space then a new object is returned, but if neither case is true it returns the original object. Since stings are immutable this won't cause a problem, and the startswith() method will fail if you try to pass it a bytes or bytearray object, but if you had written it slightly differently:
def clean(data): while data[0] == ' ': data = data[1:] while data[-1] == ' ': data = data[:-1] return data
Then the function would work with something like:
mylist = list('Hello World') stripped_list = clean(mylist)
and since lists are mutable, whether or not you return the same object could affect the program behavior if other references are kept to the original mylist, since changing stripped_list will either also affect mylist or not depending on whether it had leading or trailing elements that were a space.
-
@JITASIDA
No, you can't
That would require adding a method to a built-in type and that's not possible (without going to the C source for Python):>>> str.clean=lambda self:'clean'+self Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: can't set attributes of built-in/extension type 'str'