2

I am trying to print the filename 'xyz.0.html' in the console. It is spitting out an error "substring not found"

files in directory:

xyz.0.html
xyz.1.html
xyz.2.html

python

for name in glob.glob('*html'):
  if name.index('.0.html'):
    print name

5 Answers 5

5

Why not use str.endswith()?

>>> "xyz.0.html".endswith(".0.html")
True
Sign up to request clarification or add additional context in comments.

Comments

2

you probably want

if '.0.html' in name:

Or,

if name.endswith('.0.html'):

Your version raises an error if the substring isn't in the string (and it will evaluate to False if the substring is at the start of the string) since the index method returns the index in the string where the substring was found (or raises an exception if the substring wasn't found).

Comments

2

try

if ".0.html" in name: 
   print name

or

if name.endswith(".0.html"):
      print name

Comments

2

The error is just what it says. When you call name.index('0.html') on the name "xyz.1.html", the string is not found. index raises an error in this case. If you don't want this, you can use the find method instead (which returns -1 if the substring is not found), or you can catch the exception.

1 Comment

+1 - this is a good why, the other answers only tell you other (better) ways of doing it, not why the version in the question is wrong.
0

you can use python's generator

print [name for name in glob.glob('*html') if name.endswith(".0.html")]

2 Comments

Just to nit-pick, that's a list comprehension, not a generator. Also, that prints the names as a list compared to a vertical column of names which may or may not matter.
@mgilson thanks, but It acts like generator, and it creates a list, what is the problem of this code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.