slice operator
Python provides the slice (Slice) operator, which is very useful and can easily extract a certain sequence of numbers through slicing. For example, the first 10 numbers:
# The slice slice operator takes the first 10 elements L=list(range(0,100 )) print (L[:10]) #If the index is 0, it can be omitted >>[0, 1, 2, 3, 4, 5, 6, 7 , 8, 9]
L[0:10] means to start from index 0 (index 0 can be omitted) until index 10 (but not including index 10), which is a "left closed right open" interval [0,10), slice operator You can also take the reciprocal element, such as L[-2:-1], to get the second-to-last element 98.
Implementing the default method of strip with the slice operator
# str.strip() Remove the specified characters (strings) at the beginning and the end, the default is a space str= ' hello world! ' print (str.strip()) #Use the [:] slice operator to remove the leading and trailing spaces from the string n= 0 j =0 #Front index k=0 #After index while n< len(str): if str[n:n+1]!= ' ' : j=n break n=n+1 while n<len(str): if str[-n-1:-n]!=' ': k=-n break n=n+1 print(str[j:k]) 》hello world! 》hello world!
Advanced Edition
Implement the strip method using the [:] slice operator
#Use the [:] slice operator to implement the strip method def my_strip(str,chr=' '): n = 0 #reset loop index J=0 #front index K=0 #back index Ls=len(str) #input string length L=len(chr) #remove character length #get front index J while n< Ls : if str[n:n+L]!= chr: J=n break n=n+L n = 0 #loop index reset #get back index K while n< Ls: if str[-nL:Ls-n]!= chr: K =Ls- n break n =n+ L #return slice return str[J:K] str='0000a000' chr='000' print(my_strip(str,chr)) 》0a
Simple version
After reading the code of an old man, it is very simple and admirable. The record is as follows:
def trim(str,chr=' '): L = len(chr) while str[:L] == chr: #If the first string is a space, delete the first str = str[L:] while str[-L:] == chr : #If The last of the string is a space, delete the last str = str[:- L] return str