Python's code problem of removing spaces at the beginning and end of a string

def trim (s):

while s[:1]==" ":
    s=s[1:]
while s[-1:]==" ": -sharpwhile s[-1]==" "
    s=s[:-1]       -sharp ""  "   " IndexError: string index out of range
return s
Mar.31,2021

If i or j is negative, the index is relative to the end of sequence s: len (s) + i or len (s) + j is substituted. But note that-0 is still 0.
The slice of s from i to j is defined as the sequence of items with index k such that i < = k < j. If i or j is greater than len (s), use len (s). If i is omitted or None, use 0. If j is omitted or None, use len (s). If i is greater than or equal to j, the slice is empty.

above is the description of slicing in the document. We can see that when slicing is used, I and j before and after the colon will be judged first, so in'[- 1:], the value of I and j after judgment is equal, so the returned slice is empty and will not report an error.
in addition, if you remove the leading and trailing spaces of the string, you can consider directly using the function strip () included with str

.

isn't it good to use split with blanks removed?

Menu