What does -1 mean in this code([file for file in os.listdir(folder_dir) if file.find("xlsx") != -1])?

Viewed 88

How can you interpret the code?

[file for file in os.listdir(folder_dir) if file.find("xlsx") != -1]

Also, what does -1 mean in this code?

2 Answers

The string find function gives -1 automatically if it does not appear in the string. So your code is doing a condition (if statement) to check whether xlsx is in the string.

The str.find function is meant to find the index of the substring being in the string.

Here is an example:

>>> a = '123abc'
>>> a.find('a')
3
>>> a.find('Something that is not in the string')
-1
>>> 

As mentioned in the documentation:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

Observe that the code snippet loops through files within folder_dir using a list comprehension.

For each such file, we check whether the filename contains the substring xlsx, using str.find.

If the substring occurs in the string, it will return the first index within the string at which it occurs, otherwise, it will return -1.

From the Python documentation:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

The condition file.find("xlsx") != -1 will be True for any filename which contains xlsx, and hence the filename will be added to the list.

Hence, this code:

[file for file in os.listdir(folder_dir) if file.find("xlsx") != -1]

is simply making a list of all the files in folder_dir containing xlsx.

More generally, you'd probably want to check whether the filename ends with .xlsx instead, using str.endswith:

[file for file in os.listdir(folder_dir) if file.endswith(".xlsx")]
Related