Home > database >  for x in text - how does python know x is supposed to read a line, not a word, a letter, ...?
for x in text - how does python know x is supposed to read a line, not a word, a letter, ...?

Time:02-28

When you use a for loop in python, for example to read a txt line by line, you'd maybe write:

txt = open("SomeTextFile.txt", "r")
for x in txt:
    print (x)

Now, my question is: How does python "know" that it is supposed to read one line? Why isn't it one letter or one word?

CodePudding user response:

It depends on the type of txt, in general for loop gets one item from the pool for each iteration

>>> txt = 'bla'
>>> for x in txt: print(x)
... 
b
l
a
>>> txt = ['bla', 'foo', 'bar']
>>> for x in txt: print(x)
... 
bla
foo
bar

CodePudding user response:

I'm assuming txt is either a string read from a file, or a file object (something you created using open()).

By default, lines are separated by a newline (character '\n'). While you can think of these as what gets typed when you press the 'Enter' or 'Return' key, it's not exactly true.

In your code, Python is implicitly searching for '\n', and each time it finds one, it marks that as an element. You could very well use the .split(some_string_goes_here) method on a string and split by spaces or whatever you choose.

Many of these "lines" (or words, or whatever) are "grouped" as an iterable, so the for loop can access one at a time.

Source: https://docs.python.org/tutorial/inputoutput.html#methods-of-file-objects

CodePudding user response:

Assuming txt = open(<filename>)

You may think of a

for x in txt:
    ...

as

iterator = iter(txt)

while True:
    try:
        x = next(iterator)
        ...
    except StopIteration:
        break

iter(txt) will return iterator that iterates over file lines, so that's why you are iterating over txt lines

  • Related