SoFunction
Updated on 2024-11-18

Usage of index and seek in Python (detail)

1、index()

The general use case is to retrieve the parameter in a sequence and return the index of the first occurrence, not finding it will report an error, for example:

>>> t=tuple('Allen')
>>> t
('A', 'l', 'l', 'e', 'n')
>>> ('a')
Traceback (most recent call last):
 File "<pyshell#2>", line 1, in <module>
  ('a')
ValueError: (x): x not in tuple
>>> ('e')
3
>>> ('l')
1

But the parameter may appear many times, what to do?

The full syntax of the index() function looks like this:

(str, beg=0, end=len(string))

str - specify the string to retrieve
beg - start index, default is 0.
end - the end index, defaults to the length of the string.

So we can reset the start index to continue the search, for example:

>>> ('l',2)
2

Since the first occurrence of 'l' is at position 1, we add 1 to the start index to continue the search, and sure enough, we find 'l' again at index 2.

2、seek()

The seek() function is a function that belongs to file operations and is used to move the file read pointer to a specified location.

Grammar:

(offset[, whence])

offset - the starting offset, i.e., the number of bytes representing the offset to be moved

whence: optional, default value is 0. Give a definition to the offset parameter, indicating from which position to start offsetting; 0 means counting from the beginning of the file, 1 means counting from the current position, 2 means counting from the end of the file.

#
#first line
#second line
#third line

f=open('','r')
print(())
print(())
(0,0)
print(())
(1,0)
print(())

Console Output:

first line

second line

first line

irst line

[Finished in 0.3s]

The readline() function reads an entire line of string, so the file read pointer moves to the next line.

Above this Python index () and seek () usage (detailed) is all I have shared with you, I hope to give you a reference, and I hope you support me more.