Printing on only one line [duplicate] - python

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
Print in one line dynamically [duplicate]
(22 answers)
Closed 3 years ago.
I have a program that has to only print data onto one line.
What can I do to do this.
for i in range(10):
print(i)
Is it possible to print all of this on one line so it prints 0, erases the line, print 2, erases, etc..?

Use print(i,end="\r") to return to the start of the line and overwrite.

for i in range(10):
print(i,end=" ")
this is easiest way to print in one line.

in python 2.x:
from __future__ import print_function
for i in range(10):
print (i, end="")
in python 3.x
for i in range(10):
print (i, end="")

For this specific usecase you can do something like this:
print(*range(10))
And to update each character on the line you will need to use '\r' or the return character, that returns the position of the cursor to the beginning of the line. However, you need to be sure you count in the length of the strings you are printing, otherwise you will be overwriting only part of the string. A full proof solution will be:
import time
maxlen = 0
for i in range(12,-1,-1):
if len(str(i))>maxlen:
maxlen = len(str(i))
print(f'\r{str(i): <{maxlen}}',end = '')
time.sleep(2)
print('')
time part is added so that you can view the change. maxlen computes the maximum length string you are going to print and formats the string accordingly. Note: I have used f'strings, hence it would only work for Python 3.x

Related

how to print at same line using end parameter? [duplicate]

This question already has answers here:
How to overwrite the previous print to stdout?
(18 answers)
Closed 5 days ago.
I'd like to print at same line for print statement inside a for loop using end= parameter. not sure which end parameter i can use.
For example, in below, for each time's print, only need to change str(i) and str(result), everything is the same.
for i in range(10):
result=i**2
print('iteration is'+str(i)+' with result of '+str(result))
Thanks
Use an empty end parameter and go back the length of the previous print
L=0
for i in range(3):
result=i**2
my_str = 'iteration is'+str(i)+' with result of '+str(result)
print('\b'*L + my_str, end='')
L= len(my_str)

Print random integer and phrase in same line? [duplicate]

This question already has answers here:
How can I print multiple things on the same line, one at a time?
(18 answers)
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 1 year ago.
Not sure if this is asked before but: How do you print "searching for x" where "x" is a random integer? I have my code below:
from random import randint
numbers = []
random = randint(1,50)
for i in range(0,10):
numbers.append(randint(1,50))
for j in range(len(numbers)):
print('searching for')
print(random)
print('in')
print(numbers)
break
And this is what happens but I want "searching for __ in [list]" on the same line. Is there a way to do it?
Thanks in advance!
try this:
print(f'searching for {random} in {numbers}')
it requires python 3.6 or up and it is called an f-string
for n in numbers:
print("Searching for {} in {}".format(n, numbers))
Does that answer what you want to do?

Python - Using while loops in functions [duplicate]

This question already has answers here:
Why is "None" printed after my function's output?
(7 answers)
Closed 5 years ago.
I'm trying to create a function that uses a while loop to count up from one to a number given by a user. The code executes as I intend it to but returns None at the end. How do I get rid of the None? Here's the code.
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
print (printFunction(int(input())))
You can use this code to prevent none, tough its just the last line changed
def printFunction(n):
i = 1
while i <= n:
print(i)
i+=1
printFunction(int(input()))
In the last line you were using
print(printFunction(int(input()))) which was getting you None after printing the results.
Instead just use printFunction(int(input())). This will not print None. You can also use a message to ask user like printFunction(int(input("Enter a number"))). Since there is noting getting returned you no need to use print.

How to add comma in print statement in Python [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print variable and string on same line in Python? [duplicate]
(18 answers)
Closed 5 years ago.
I'm new to python and learning how to code.
I'm printing last element of my list and sum of the list as-
print list[-1],sum
But the output is separated by " " and not separated by ",".
Any idea how to separate it by comma?
I'm using Python 2.7
Include it in quotes, like this:
print str(list[-1]) + "," + str(sum)
Enclosing them in str() is unnecessary if list[-1] and sum are strings.
In general, symbols are interpreted as Python symbols (for example, names like sum are interpreted as variable or function names). So whenever you want to print anything as is, you need to enclose it in quotes, to tell Python to ignore its interpretation as a Python symbol. Hence print "sum" will print the word sum, rather than the value stored in a variable called sum.
You'll have to compose that together into a string. Depending on what version of Python you're using, you could either do:
print "{},{}".format(list[-1], sum)
or
print "%s,%s" % (list[-1], sum)
If you were using Python3.6+, there would be a third option:
print(f"{list[-1]},{sum}")
Use the sep keyword argument:
print(list[-1], sum, sep=',')
You can use str.format() and pass whatever variables you want to get it formatted, for example:
x = 1
z = [1, 2, 3]
y = 'hello'
print '{},{},{}'.format(x, z[-1], y)
# prints: 1,3,hello

Print updating variable in the same line [duplicate]

This question already has answers here:
How do I write output in same place on the console?
(9 answers)
Closed 6 years ago.
What I'm trying to code is pretty simple:
I want to print an iteration variable, but I don't want all the lines printed for each loop, I want that will update the previous one.
Example:
for i in range(0,2000):
print 'number is %d', %i
Wrong result:
number is 0
number is 1
number is 2
number is 3
number is 4
number is 5
number is 6
...
...
What I want is:
number is 0
At the second iteration:
number is 1 `(it will replace 0 and I don't want the previous 0 anymore).`
It will be something like updating percentage of something in only one line.
Does a function exist for it in Python?
This will do the trick, and update every 1 second:
import sys
import time
for i in range(0,2000):
sys.stdout.write('\rnumber is %d' %i)
sys.stdout.flush()
time.sleep(1)
You can try something from this thread on clearing the terminal, or something from the one that fuglede posted as duplicated.
The following code worked fine for me in a mac, but if you remove the time.sleep() it will just run so fast that you wont even see the prints.
import time, sys
for i in range(0, 20):
print 'Number is: %d' % i
time.sleep(.1)
sys.stderr.write("\x1b[2J\x1b[H")
What you want is called the Carriage Return, or \r
Use:
for i in range(0,2000):
print "number is %d \r" %i,
The spaces will keep the line clear from prior output.

Categories