Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
282 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65662235/what-does-1-mean-in-this-codefile-for-file-in-os-listdirfolder-dir-if-file

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...