New to Python. For in loops curiosity

John Gordon gordon at panix.com
Tue May 13 23:46:30 EDT 2014


In <2f08e970-1334-4e7f-ba84-14869708a73b at googlegroups.com> Leonardo Petry <leonardo.petry.br at gmail.com> writes:

> fin = open('wordplay.txt');
> user_input = raw_input('Enter some characters: ')
> count = 0
> for line in fin:
>     word = line.strip()
>     if(avoids(word, user_input)):
>     	count += 1;

> This is just too convenient. 
> Basically my question is: Why is python not treating the contents of
> wordplay.txt as one long string and looping each character?

> Any comment is greatly appreciate. Thanks

Your code is not treating the contents of wordplay.txt as one long string
because 'for line in fin:' tells it to read line-by-line.

If you want to read the entire contents, use the read() method:

    file_content = fin.read()

-- 
John Gordon         Imagine what it must be like for a real medical doctor to
gordon at panix.com    watch 'House', or a real serial killer to watch 'Dexter'.




More information about the Python-list mailing list