I want to print the looped output to the screen on the same line.
How do I this in the simplest way for Python 3.x
I know this question has been asked for Python 2.7 by using a comma at the end of the line i.e. print I, but I can’t find a solution for Python 3.x.
i = 0
while i <10:
i += 1
## print (i) # python 2.7 would be print i,
print (i) # python 2.7 would be 'print i,'
Screen output.
1 2 3 4 5 6 7 8 9 10
What I want to print is:
12345678910
New readers visit this link aswell http://docs.python.org/release/3.0.1/whatsnew/3.0.html
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
From help(print):
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
You can use the end keyword:
>>> for i in range(1, 11): ... print(i, end='') ... 12345678910>>>
Note that you’ll have to print() the final newline yourself. BTW, you won’t get “12345678910” in Python 2 with the trailing comma, you’ll get 1 2 3 4 5 6 7 8 9 10 instead.
Method 2
* for python 2.x *
Use a trailing comma to avoid a newline.
print "Hey Guys!", print "This is how we print on the same line."
The output for the above code snippet would be,
Hey Guys! This is how we print on the same line.
* for python 3.x *
for i in range(10):
print(i, end="<separator>") # <separator> = n, <space> etc.
The output for the above code snippet would be (when <separator> = " "),
0 1 2 3 4 5 6 7 8 9
Method 3
Similar to what has been suggested, you can do:
print(i, end=',')
Output: 0,1,2,3,
Method 4
print("single",end=" ")
print("line")
this will give output
single line
for the question asked use
i = 0
while i <10:
i += 1
print (i,end="")
Method 5
You can do something such as:
>>> print(''.join(map(str,range(1,11))))
12345678910
Method 6
>>> for i in range(1, 11): ... print(i, end=' ') ... if i==len(range(1, 11)): print() ... 1 2 3 4 5 6 7 8 9 10 >>>
This is how to do it so that the printing does not run behind the prompt on the next line.
Method 7
Lets take an example where you want to print numbers from 0 to n in the same line. You can do this with the help of following code.
n=int(raw_input())
i=0
while(i<n):
print i,
i = i+1
At input, n = 5
Output : 0 1 2 3 4
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0