python - print iteration number without new line [duplicate] - python

This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed last month.
I have a loop:
for i in range(10):
print i
and it print :
1
2
...
8
9
OK
but I'm searching to make a unique line which actualize for each iteration like this :
for i in range(10):
magic_print "this is the iteration " + i + " /10"
with a result like:
"this is the iteration <i> /10"
<i> changing dynamically
Thanks !

As I understand your question, you would like to overwrite previous prints and count up. See this answer: https://stackoverflow.com/a/5419488/4362607
I edited the answer according to PM 2Ring's suggestions. Thanks!
import sys
import time
def counter():
for x in range(10):
print '{0}\r'.format(x),
sys.stdout.flush()
time.sleep(1)
print
counter()

the solution is the format function from the str object
for i in range(10):
print "this is the iteration {} /10".format(i)

Related

print down the line and automatically updated continuouslyin [duplicate]

This question already has answers here:
Python 3 Print Update on multiple lines
(2 answers)
Closed 1 year ago.
i have a command
import time
i=0
b=0
while(True):
i=i+1
b=b+1
time.sleep(2)
print('Jack: {} '.format(str(i)) ,end='')
print('Han: {} '.format(str(b)) ,end='\r')
i want print this like
Jack: 1
Han : 1
in the next loop it still prints at that position only the number changes like this
Jack: 2
Han : 2
Note: Do not combine 2 prints into 1 print
I need ideal
If I read what you want correctly, you want to update the number, not print a new line. In which case use blessings and print at the location on the screen instead.
Something like:
from blessings import Terminal
from time import sleep
term = Terminal()
i = 0
while True:
print(term.move(1, 1), f"I am a number: {i}")
i += 1
sleep(1)
Note that there are other terminal control libraries, I just like blessings.

Python Random variable printing back "None" [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 2 years ago.
I'm basically trying to create something of an mad libs generator. When it runs through all the random variables, and I try to get it to save as a variable, and then print that variable I get "none"
I'm a novice so I apologize if this is painfully dumb. Link to colab notebook where you can see it: https://colab.research.google.com/drive/1Eh0-ACUJOduxjRbsql7ut_VgZEE4PBWW?usp=sharing
This is the code
import random
#Word Buckets
list = ("Todd", "Jill","Mary")
secondlist = ("hot","cold","run" )
thirdlist = ('pizza','pasta',"wine" )
#Create Define random choices
def def1 ():
d=random.choice(list)
a=random.choice(secondlist)
r=random.choice(thirdlist)
c=random.choice(list)
print(d,a, (r+"'s"),c)
def def2 ():
d=random.choice(list)
a=random.choice(secondlist)
f=random.choice(thirdlist)
fv=random.choice(thirdlist)
print(fv, "Because of",(d+"'s"),f)
titletype = (def1, def2)
#random.choice(titletype)()
message=random.choice(titletype)()
print(message)
And that will return
None
def2 and def1 should return instead of print

Python-3.x time.sleep() wont work for print to file [duplicate]

This question already has answers here:
How can I flush the output of the print function?
(13 answers)
Closed 2 years ago.
I would like to code a python that adds every x seconds a value.
But when I add the time.sleep(x) theres no output into the .txt file anymore.
And is there a way to stop the loop after a certain time?
Code:
f = open('Log.txt','a')
while True:
print("This prints once a second.", file=f)
time.sleep(1)
Maybe something like this:
import time
while True:
with open('Log.txt','a') as f:
f.write("This prints once a second.\n")
time.sleep(1)
If you want to stop after a given time:
import time
stop_after = 10 # seconds
start = time.time()
while time.time() - start < stop_after:
with open('Log.txt','a') as f:
f.write("This prints once a second.\n")
time.sleep(1)
It is best to use a context manager, and this works:
import time
while True:
with open('Log.txt','a') as f:
print("This prints once a second.",file=f)
time.sleep(1)

Getting the match number when passing a function in re.sub [duplicate]

This question already has an answer here:
Replace part of a string in python multiple times but each replace increments a number in the string by 1
(1 answer)
Closed 2 years ago.
When using a function in re.sub:
import re
def custom_replace(match):
# how to get the match number here? i.e. 0, 1, 2
return 'a'
print(re.sub(r'o', custom_replace, "oh hello wow"))
How to get the match number inside custom_replace?
i.e. 0, 1, 2 for the three "o" of the example input string.
NB: I don't want to use a global variable for this, because multiple such operations might happen in different threads etc.
Based on #Barmar's answer, I tried this:
import re
def custom_replace(match, matchcount):
result = 'a' + str(matchcount.i)
matchcount.i += 1
return result
def any_request():
matchcount = lambda: None # an empty "object", see https://stackoverflow.com/questions/19476816/creating-an-empty-object-in-python/37540574#37540574
matchcount.i = 0 # benefit : it's a local variable that we pass to custom_replace "as reference
print(re.sub(r'o', lambda match: custom_replace(match, matchcount), "oh hello wow"))
# a0h hella1 wa2w
any_request()
and it seems to work.
Reason: I was a bit reluctant to use a global variable for this, because I'm using this inside a web framework, in a route function (called any_request() here).
Let's say there are many requests in parallel (in threads), I don't want a global variable to be "mixed" between different calls (since the operations are probably not atomic?)
There doesn't seem to be a built-in way. You can use a global variable as a counter.
def custom_replace(match):
global match_num
result = 'a' + str(match_num)
match_num += 1
return result
match_num = 0
print(re.sub(r'o', custom_replace, "oh hello wow"))
Output is
a0h hella1 wa2w
Don't forget to reset match_num to 0 before each time you call re.sub() with this function.
You can use re.search with re.sub.
def count_sub(pattern,text,repl=''):
count=1
while re.search(pattern,text):
text=re.sub(pattern,repl+str(count),text,count=1)
count+=1
return text
Output:
count_sub(r'o', 'oh hello world')
# '1h hell2 w3rld'
count_sub(r'o', 'oh hello world','a')
# 'a1h hella2 wa3rld'
Alternative:
def count_sub1(pattern,text,repl=''):
it=enumerate(re.finditer(pattern,text),1)
count=1
while count:
count,_=next(it,(0,0))
text=re.sub(pattern,repl+str(count),text,count=1)
return text
Output:
count_sub1(r'o','oh hello world')
# '1h hell2 w3rld'
count_sub1(r'o','oh hello world','a')
# 'a1h hella2 wa3rld'

What is Pythonic way to test size of a generator, then display it? [duplicate]

This question already has answers here:
Length of generator output [duplicate]
(9 answers)
How to look ahead one element (peek) in a Python generator?
(18 answers)
How to print a generator expression?
(8 answers)
Closed 8 years ago.
Yesterday I have been implementing a small Python scripts that checks difference between two files (using difflib), printing the result if there is any, exiting with code 0 otherwise.
The precise method, difflib.unified_diff() is returning a generator on the diffs found. How can I test this generator to see if it needs to be printed? I tried using len(), sum() to see what was the size of this generator but then it is impossible to print it.
Sorry to ask such a silly question but I really don't see what is the good practice on that topic.
So far this is what I am doing
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
if (len(list(diff))):
print("Differences found!")
# Recomputing the generator again: how stupid is that!
diff = difflib.unified_diff(fromlines, tolines, n=0)
sys.stdout.writelines(diff)
else:
print("OK!")
You're already converting your generator to a list, so you don't need to rebuild it.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
if diff:
...
sys.stdout.writelines(diff)
else:
...
You don't even need to convert the generator to a list if you don't want by using a simple flag:
diff = difflib.unified_diff(fromlines, tolines, n=0)
f = False
for line in diff:
if not f:
print("Differences found!")
f = True
sys.stdout.write(line)
if not f:
print("OK!")
You could convert the generator into a list.
diff = list(difflib.unified_diff(fromlines, tolines, n=0))
I think you can't, and the proper way is probably to generate all data until you raise StopIteration and then get the length of what you have generated.
What's wrong with :
import difflib
import sys
fromlines = open("A.csv").readlines()
tolines = open("B.csv").readlines()
diff = difflib.unified_diff(fromlines, tolines, n=0)
difflines = list(diff)
if len(difflines) :
sys.stdout.writelines(difflines)
else:
print("OK!")

Categories