of explains the usage of index of and seek of in Python

  • 2020-05-30 20:32:29
  • OfStack

1, index ()

1 general use is to retrieve the parameters in the sequence and return the index of the first occurrence. If it is not found, an error will be reported, such as:


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

But the parameter might come up a lot of times, so how do you do that?

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

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

The str wok specifies the retrieved string
The beg wok starts the index, which defaults to 0.
Ends the index with end, which defaults to the length of the string.

So we can reset the starting index to continue the search, such as:


>>> t.index('l',2)
2

Since the first 'l' occurs at 1, we will start index plus 1 and continue looking. Sure enough, we find 'l' at 2.

2, seek ()

The seek() function is a function in a file operation that moves the file read pointer to the specified location.

Grammar:

fileObject.seek(offset[, whence])

The offset at the beginning of the offset wok, which represents the number of bytes that need to be moved

whence: optional, default value is 0. Give the offset parameter one definition, indicating where to start the offset; 0 means counting from the beginning of the file, 1 means counting from the current location, and 2 means counting from the end of the file.

demo.py


#test.txt
#first line
#second line
#third line

f=open('test.txt','r')
print(f.readline())
print(f.readline())
f.seek(0,0)
print(f.readline())
f.seek(1,0)
print(f.readline())

Console output:


first line

second line

first line

irst line

[Finished in 0.3s]

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


Related articles: