top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Loops in Python: Why is python not treating the contents as one long string?

+1 vote

Here is something I found curious about python loops.

This loop run each character in a string

def avoids(word,letters):
 flag = True
 for letter in letters:
 if(letter in word):
 flag = False
 return flag

The loop below (at the bottom) runs each line of the file

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.

posted May 14, 2014 by Luv Kumar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

Because the iterator for file-like objects iterates over lines, not characters.

answer May 14, 2014 by Seema Siddique
+1 vote

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 =
answer May 14, 2014 by Arjuna
Similar Questions
+2 votes

I have a multi-line string and I need to remove the very first line from it. How can I do that? I looked at StringIO but I can't seem to figure out how to properly use it to remove the first line.

+2 votes

I'm trying to search for several strings, which I have in a .txt file line by line, on another file. So the idea is, take input.txt and search for each line in that file in another file, let's call it rules.txt.

So far, I've been able to do this, to search for individual strings:

import re
shakes = open("output.csv", "r")

for line in shakes:
 if re.match("STRING", line):
 print line,

How can I change this to input the strings to be searched from another file?

+3 votes

Given input as a string, return an integer as the sum of all numbers found in the string

Input: xyzonexyztwothreeeabrminusseven
Output : 1 + 23 + (-7) = 17

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.