search

Python slice index usage

Jun 04, 2018 pm 06:00 PM
pythonsliceusage

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Is Tuple Comprehension possible in Python? If yes, how and if not why?Is Tuple Comprehension possible in Python? If yes, how and if not why?Apr 28, 2025 pm 04:34 PM

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)

What are Modules and Packages in Python?What are Modules and Packages in Python?Apr 28, 2025 pm 04:33 PM

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.

What is docstring in Python?What is docstring in Python?Apr 28, 2025 pm 04:30 PM

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

What is a lambda function?What is a lambda function?Apr 28, 2025 pm 04:28 PM

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

What is a break, continue and pass in Python?What is a break, continue and pass in Python?Apr 28, 2025 pm 04:26 PM

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

What is a pass in Python?What is a pass in Python?Apr 28, 2025 pm 04:25 PM

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.

Can we Pass a function as an argument in Python?Can we Pass a function as an argument in Python?Apr 28, 2025 pm 04:23 PM

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

What is the difference between / and // in Python?What is the difference between / and // in Python?Apr 28, 2025 pm 04:21 PM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

MantisBT

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

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

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.