Using the slicing operation, a trim () function is implemented to remove the spaces at the beginning and end of the string.

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"?

Mar.03,2021

will re-execute this function after knowing whether trim (s), is returned after executing elif. Isn't that right?


mm-hmm, this takes advantage of the nesting of functions


this is actually a recursion, such as s = 'hello', enters the trim, for the first time and enters the else branch for the second time, and then enters the trim, for the second time. When you enter the trim for the second time, the fragment (s [:-1]) removes the last character, that is,''is removed, so when you enter trim for the second time, you get rid of the last character (s [:-1]), so when you enter trim for the second time, you get rid of the last character. The if condition is true and returns' hello'


Why are there two spaces in quotation marks instead of one? when I write, only two spaces can run successfully, and one space can't


def trim (s):

 if s[:1] != ' ' and s[-1:] != ' ':
     -sharps
     return s
 elif s[:1] == ' ':
     -sharps[0]s[1]
     return trim(s[1:])
     -sharps[0]s = s[1:]
 else:
     -sharps[-1]
     return trim(s[:-1])
     -sharps[-1],s = s[:-1]

-I am a split line-
pycharm add breakpoints, use the following test statement to feel:)
-I am also a split line-

if trim ('hello world')! =' hello world':

 print('4!')

else:

 print('!')
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b37a31-2c0a7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b37a31-2c0a7.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?