This article mainly introduces the usage of Python slice index, and analyzes the common usage methods and operation precautions of Python slice index in detail in the form of examples. Friends in need can refer to it
The examples in this article describe Python slices Index usage. Share it with everyone for your reference, the details are as follows:
In Python, you can access each element of the sequence by using simple square brackets plus a subscript. This method is called the slicing operator, slicing The operator has three forms:
[], [:], [ ::]
The syntax for accessing a certain data element is as follows:
sequence[index]
sequence is the name of the sequence, index is the corresponding offset of the accessed element, which is a positive number, 0; use negative When indexing, the range is -len(sequence)
Since Python is object-oriented, you can also add it directly after the sequence An index is accessed, as follows
print ('a','b','c','d')[2]
For the case of accessing multiple elements
sequence[starting_index:ending_index]
The following are some examples of access methods:
sequence="abcdefgh" print len(sequence) #显示序列长度 print sequence #打印完整序列 print sequence[:] print sequence[2:3] #切片显示,不指定步长默认为1,指定了步长(这里是setp为2)按照步长进行显示 print sequence[1:6:2] print sequence[3] #元素访问 print sequence[0:3] #从首元素开始访问,访问区间为[0,3),左开you print sequence[:3] print sequence[2:8] #从第二个元素一直访问到最后一个元素 print sequence[2:] print sequence[::-1] #从最后一个元素开始访问,逆序访问,可以视为“翻转”操作 print max(sequence) print min(sequence) print sequence.index('c')
What should be noted here is the repetition operator *
sequence * copies_int
When multiple copies of a sequence are required, the repeat operator comes into play, copies_int must For integer
print sequence*3 #使用重复操作符
Connection operator
sequence1 sequence2
It is allowed to connect two sequences of the same type
print sequence + sequence
But note that it seems very convenient, but this operation is not the fastest or most efficient. For strings, this operation is not as good as putting all substrings into a list or iterable object, and then using the join()
method to join all the contents together to save memory; for lists Generally speaking, it is recommended to use the extend()
method of the list type to merge two or more list objects
str.join(sequence) #方法用于将序列中的元素以指定的字符连接生成一个新的字符串
str = "-"; seq = ("a", "b", "c"); # 字符串序列 print str.join( seq );
The output is:
a-b-c
list.extend(seq) #函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)
aList = [123, 'xyz', 'zara', 'abc', 123]; bList = [2009, 'manni']; aList.extend(bList) print "Extended List : ", aList ;
The output is :
Extended List : [123, 'xyz', 'zara', 'abc', 123, 2009, 'manni']
The syntax of slice index is much more flexible than the simple single element index method. The start and end index values can exceed the length of the string. That is, the starting index value can be less than 0, and the ending index value can be greater than the length of the sequence, such as:
print ('Faye','Leanna','Daylen')[-100:100]
The output is:
('Faye', 'Leanna', 'Daylen')
If there is a string, and you want to display it through a loop in this way: cut off the last character every time, how to achieve this?
sequence = 'abcdef' i = -1 for i in range(-1,-len(sequence),-1): print sequence[:i]
The output is:
abcde abcd abc ab a
It is found that the first one is not displayed, that is, the complete string is not displayed, unless another separate one is defined sequence[:0]
, use None as the index value here
sequence = 'abcdef' for i in [None] + range(-1,-len(sequence),-1): print sequence[:i]
The output is:
abcdef abcde abcd abc ab a
The above is the detailed content of Python slice index usage. For more information, please follow other related articles on the PHP Chinese website!

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.

Article discusses lambda functions, their differences from regular functions, and their utility in programming scenarios. Not all languages support them.

Article discusses break, continue, and pass in Python, explaining their roles in controlling loop execution and program flow.

The article discusses the 'pass' statement in Python, a null operation used as a placeholder in code structures like functions and classes, allowing for future implementation without syntax errors.

Article discusses passing functions as arguments in Python, highlighting benefits like modularity and use cases such as sorting and decorators.

Article discusses / and // operators in Python: / for true division, // for floor division. Main issue is understanding their differences and use cases.Character count: 158


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
