stay Python in , Slices are lists , Common usage in tuples or strings , However, for some beginners , Sometimes the readability of code with slices is not very friendly . Let's talk about it Python The specific usage of slicing in Chinese .
stay Python in , The use of slices is [ Starting position : End position : step ]
, Represents all the elements obtained from the start position to the end position according to the step size . among , Starting position , End position , All three properties have default values , When its specific value is not specified ,Python The default value is used , Their default values are 0,, List or tuple length ,1.
It is worth noting that ：
1, When the starting position is negative , For example, the starting position is -k Time , The last list is taken , The last character in a tuple or string k Elements .
2, When the step size is negative , Indicates counting from back to front , Its absolute value is still the interval .
Here are a few demo to glance at .
rlist=list(range(10)) # What is generated is [0,1,2,3,4,5,6,7,8,9] print(rlist[2:8])
# From the first 3 Start with two elements , To the third 8 End of element print(rlist[:5]) # If it's not before the colon , Representative from 0 I started to take it print(rlist[4:])
# If it's not after the colon , The representative gets to the end print(rlist[:]) # If there's no colon before or after it , The representative takes all b = a[i:j]
# Means copy a[i] reach a[j-1], To generate a new list object a = [0,1,2,3,4,5,6,7,8,9] b = a[1:3] #[1,2]
# When i by default , Default to 0, Namely a[:3] amount to a[0:3] # When j by default , Default to len(alist), Namely a[1:] amount to a[1:10]
# When i,j All default ,a[:] It's like a complete copy a b = a[i:j:s] # express ：i,j Same as above , but s Represents step , Default to 1.
# therefore a[i:j:1] amount to a[i:j] # When s<0 Time ,i by default , Default to -1. j by default , Default to -len(a)-1 # therefore a[::-1] amount to
a[-1:-len(a)-1:-1], That is, copy from the last element to the first , That is the reverse order .
Here is an interesting question ：
# Determine whether a string is palindrome , Namely ： Is the string equal to its inverted string , If it is equal, it is palindrome . s=' Shanghai's tap water comes from the sea ' # Palindrome algorithm , On the other hand, it's the same in the past for
i in range(10): s = input(' Please enter a string ：') if len(s)<2: print(' String length must be greater than 2') elif
s==s[::-1]: #.reverse() Methods are methods in the list , Not in string , Therefore, only slice method can be used print(' It's palindrome ') else:
print(' It's not palindrome ')
end , Thank you for reading ! If there is a mistake , Please correct me !