-2

I want to store all the "o"'s printed by stdout.write function into a a variable which could be accesable any time

I have tried using len function to break loop once it reaches certain amount of strings, but no luck

import time
import sys


while True:
    sys.stdout.write("o")
    sys.stdout.flush()
    time.sleep(0.05)

3 Answers3

1

Very simply, you can add them to a string, one at a time:

record = ""
while True:
    sys.stdout.write("o")
    sys.stdout.flush()
    record += 'o'
    time.sleep(0.05)

A slightly faster way is to count the quantity written, and then produce your desired string:

count = 0
while True:
    sys.stdout.write("o")
    sys.stdout.flush()
    count += 1
    time.sleep(0.05)
    # Insert your exit condition

record = 'o' * count
Prune
  • 76,765
  • 14
  • 60
  • 81
0

Keep on appending values to a string. Check the length and break when desired.

import time
import sys

data = ""
while True:
    temp = "o"
    data += temp
    sys.stdout.write(temp)
    sys.stdout.flush()
    time.sleep(0.05)
    if(len(data)==10):
        break;
fiveelements
  • 3,649
  • 1
  • 17
  • 16
0

You could keep track of the number of O's in a separate variable:

number_of_os = 0

while True:
    sys.stdout.write("o")
    sys.stdout.flush()
    number_of_os += 1
    if number_of_os >= 100:
        break
    time.sleep(0.05)
John Gordon
  • 29,573
  • 7
  • 33
  • 58