First determines whether the length of the string is 0, if it is, return the string directly
The second cycle is determined whether the string header spaces, and if so, remove spaces, and then determines whether the length of the string is 0, if it is, return the string directly
Third, aft cycle determines whether the string has spaces, and if so, remove spaces, and then determines whether the length of the string is 0, if it is, return the string directly
Finally, return the string
Code:
def trim(s): if len(s) == 0: return s while s[0] == ' ': s = s[1:] if len(s) == 0: return s while s[-1] == ' ': s = s[:-1] if len(s) == 0: return s return s
Test code:
IF TRIM ( ' Hello ' !) = ' Hello ' : Print ( ' test failed! ' ) elif TRIM ( ' Hello ' ) =! ' Hello ' : Print ( ' test failed! ' ) elif TRIM ( ' Hello ' )! = ' Hello ' : Print ( ' ! test failed ' ) elif TRIM ( ' hello world ' !) = ' Hello World ' : Print ( ' ! Test failed ' ) elif TRIM ( ' ' ) =! ' ' : Print ( ' ! Test failed ' ) elif TRIM ( ' ' ) =! ' ' : Print ( ' test failed! ' ) the else : Print ( ' test successfully! ' )