[Tutor] Iteration issues
Alan Gauld
alan.gauld at yahoo.co.uk
Thu Jun 7 18:52:20 EDT 2018
On 07/06/18 23:21, Roger Lea Scherer wrote:
> they won't. I've started from scratch again.
>
> **********
> import string
>
> gettysburg =
> open("C:/Users/Roger/Documents/GitHub/LaunchCode/gettysburg.txt", "r")
>
> puncless = ""
> for char in gettysburg:
I think this is wrong. gettysburg is a file and the iterator for
a file returns a string, so "char" should probably be "line".
Either that or you need to call read() on the file first.
> if char in string.punctuation:
> gettysburg.replace(char, "")
But this is also dodgy since you are changing the thing you are
itrerating over. That's a bit like cutting off the branch of a
tree that you are sitting on - bad things can happen. And to
further confuse matters strings are immutable so the replace
returns a new string which you throw away.
But you don't really need to replace the char in the original
you just need to ignore it:
for char in gettysburg.read():
if char not in string.punctuation:
puncless += char
print(puncless)
--
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