What is the difference between a string defined within a text file and another defined as a variable?

Asked

Viewed 98 times

2

Imagine the following:

texto = "They fly quickly over the snow in their sledges; the motion is pleasant, and, in my opinion, far more agreeable than that of an English stagecoach"

texto1 = open("sample.txt")

where sample.txt has the same content as the text variable above

In doing

for i in texto:
     print(i)

is printed character by character.

Unlike:

for i in texto1:
     print(i)

The full text is printed. Why?

2 answers

7


The difference is the type of object you are iterating.

In the first example your repetition loop is iterating over a string, that when iterated generates as output the characters one by one. This behavior is defined in the Python C API itself, as language specification.

In the second example the loop of repetition is iterating over the function return open, which is an object file-like; i.e., an object that implements the class io.IOBase, that due to its implementation is an eternal object that generates at each iteration a line of content.

That is, in the first you iterate only on a string simple, while in the second you iterate over a file, line by line. Since your file only has one line, the entire content is displayed in the first iteration.

To arrive at an equivalence between the two examples, in the second you should first load all content in memory, in the form of string.

texto1 = open('sample.txt').read()
# O método read lê o arquivo inteiro

for i in texto1:
    print(i)
  • He was faster than me... :(

  • 1

    Easy, but complete questions where you don’t need to go around and explain the basics of programming are missing around here - -it’s everyone upstairs. : -D

  • But look, even jsbueno came out, it wasn’t just me then. D

  • Woss, you were too quick kkk Ta crazy xD

1

The string defined in the variable and the one coming from the text has no difference.

What the function open() returns is an object of<class '_io.TextIOWrapper'>, where you can get the file string using one of these methods: read, readline, readlines. That is, what you get from this function, is not a string !!

Other than that, this object is also an eternal, and you can through for loop go through each line of the file. So in your example, the string is printed completely, because every time for loop gives, it returns a complete row of your file.

In the example of the string you define in its variable, it prints each letter because strings are also iterable objects (sequence) and when performing a for loop with them, you will get in each round an element of the string.

Example:

variavel = "Olá!\n Como você está ?"

file = open("arquivo.txt") # Mesmo conteúdo da variável.

for linha in file:
    print("Nova linha:",linha)

    # Já que a variável "linha" é uma string, vamos passar ela em um for loop.

    for letra in linha:
        print("Letra da linha:",letra)

    print("-----------------------------")

file.close()

The way out of this will be:

Nova linha: Olá!

Letra da linha: O
Letra da linha: l
Letra da linha: á
Letra da linha: !
Letra da linha: 

-----------------------------
Nova linha:  Como você está ?
Letra da linha:  
Letra da linha: C
Letra da linha: o
Letra da linha: m
Letra da linha: o
Letra da linha:  
Letra da linha: v
Letra da linha: o
Letra da linha: c
Letra da linha: ê
Letra da linha:  
Letra da linha: e
Letra da linha: s
Letra da linha: t
Letra da linha: á
Letra da linha:  
Letra da linha: ?
----------------------------- 
  • 2

    Good answer Jean, but if you allow me to give a hint I would not call sequences or objects file-like from "iterators", but from "iterators"... For iterators are objects apart, which you receive using iter(). You can even test in the terminal: type("teste") results in <class 'str'>, while type(iter("teste")) results in <class 'str_iterator'>.

  • Really, I hadn’t thought of that. Thank you, I will correct the answer ;-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.