1. Recently, I have studied python, again to see the slicing part of Liao Xuefeng"s tutorial. I would like to ask how this code realizes that the spaces on both sides are not displayed in the output by slicing
.
def trim(s):
if s[:1] != " " and s[-1:] != " ":
return s
elif s[:1] == " ":
return trim(s[1:])
else:
return trim(s[:-1])
if there are spaces on one side of the input string, I can also understand how the code works, but if there are spaces on both sides of the string, I don"t understand why there are no spaces on both sides of the final output. For example, s = "hello", how does this code become " hello"
when output? Because my understanding is that if the string is" hello", if does not execute, and after elif executes, it returns" hello". The last else is not executed either, so why is the result still "hello"?