@Drizzel said:
def clean(data):
while data.startswith(' '): data = data[1:]
while data.endswith(' '): data = data[:-1]
return data
Just 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.