[Tutor] String Attribute

Alan Gauld alan.gauld at btinternet.com
Sat Aug 1 01:54:51 CEST 2015


On 31/07/15 19:57, ltc.hotspot at gmail.com wrote:

> for line in fh:
>   line2 = line.strip()
>   line3 = line2.split()
>   line4 = line3[0]

You need to check that there actually is something
in the list to access. If you get a line with only
one word in it, or even a blank line this will fail.


>   addresses.add(line4)
>   count = count + 1
> print "There were", count, "lines in the file with From as the first word"

Despite what you print you don't know that its true anymore.
You have removed the code that tested for the first
word being "From". You should put that check back in your code.

> →I entered different index ranges from  [] to [5]

I'm not sure what [] means in this case? It should be a syntax error
as you show below.

> In [34]: print line3[]
>    File "<ipython-input-34-7bf39294000a>", line 1
>      print line3[]
>                  ^
> SyntaxError: invalid syntax

See, that's not an IndexError. They are different and have different 
causes. A syntax error means your code is not valid Python. An
IndexError means the code is valid but its trying to access
something that doesn't exist.

> →Question: I think the problem is in the placement of the address set: The addresses = set()?

No it has nothing to do with that. The set is not
involved in this operation at this point.

To debug these kinds of errors insert a print statement
above the error line. In this case:

print line3

That will show you what the data looks like and you can tell
whether line3[1] makes any kind of sense.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list