How to print spaces between values in loop? - python

How to put spaces between values in a print() statement
for example:
for i in range(5):
print(i, sep='', end='')
prints
012345
I would like it to print
0 1 2 3 4 5

While others have given an answer, a good option here is to avoid using a loop and multiple print statements at all, and simply use the * operator to unpack your iterable into the arguments for print:
>>> print(*range(5))
0 1 2 3 4
As print() adds spaces between arguments automatically, this makes for a really concise and readable way to do this, without a loop.

>>> for i in range(5):
... print(i, end=' ')
...
0 1 2 3 4
Explanation: the sep parameter only affects the seperation of multiple values in one print statement. But here, you have multiple print statements with one value each, so you have to specify end to be a space (per default it's newline).

Just add the space between quotes after the end. It should be:
end = " "

In Python 2.x, you could also do
for i in range(5):
print i,
or
print " ".join(["%s"%i for i in range(5)])

Related

Increasing understanding of printing multiple variables [duplicate]

for example in this code below the with the end the integers stay on the same line but without the it does not.
num = 5
for i in range(1, num +1):
for j in range(num, i-1, -1):
print(j, end="")
print()
The end statement for printing in Python allows the programmer to define a custom ending character for each print call other than the default \n
For instance, if you have a function that is to print all values within a list on the same line, you do:
def value(l):
for items in l:
print(l, end=' ')
So if the list argued to this function contains the values [1, 2, 3, 4], it will print them in this manner: 1 2 3 4. If this new ending character parameter was not defined they would be printed:
1
2
3
4
The same principle applies for ANY value you provide for the end option.
In Python 3, the default ist end='\n' for the print function which is a newline after the string is printed.
To suppress this newline, one can set end='' so that the next print starts in the same line.
This is unrelated to the for loop.

Python - Removing whitespace on output

So, I have this code:
print("%d" % a, end=(" "))
It works, but in the output, there's a whitespace after the last number. I need to get rid of the last whitespace. My output needs to be shown on the same line, separated by a blank space. There should be no space after the last value.
Here's an example: (n is input, so suppose n = 5)
0 1 1 2 3
I've tried .strip, .join, but none of them worked. What do i have to do to get the right output? I'm sorry if this is too much of a simple question, I'm new in python.
edit: edit2:
a, b, i = 0, 1, 0
n=int(input())
for j in range(0, n):
while i < n:
print("%d" % a)
a, b = b, a + b
i += 1
You are adding the trailing space yourself with the end argument.
print("%d" % a, end=(" "))
Means print a ending in a ' '. Remove the end argument and the trailing space will no longer be printed (the default '\n' will be printed instead). See the docs for print() for more details.
Note also, that the end argument does not affect the string you are printing, i.e., a is not affected by end. If there is a trailing space in a string a, then a.strip() will remove that space. The reason it doesn't get removed by strip() in your case is that the space is not in the string you are printing, but instead is added to the visual output by the print() function.
Update:
It is hard to say, because it is a mystery what happens before or after the code snippet in your edit, but it sounds like you want to do something like:
a, b, i = 0, 1, 0
n=int(input())
nums = []
for j in range(0, n):
while i < n:
nums.append(str(a))
...
# Based on your desired output,
# I assume you modify the value of `a` somwhere in here
...
print(' '.join(nums))

printing list elements side by side -- file operations

j=0
while j<5:
random_lines=random.choice(men_heroes_lines)
element=(random_lines.split(":")[0:1])
random_lines_women=random.choice(women_heroes_lines)
element_women=(random_lines_women.strip("\n").split(":")[0:1])
print element
print element_women
j=j+1
hey guys here is my question.. i have two txt files which contains men and women names..
as:
manname1: a b c d
manname2: x y z e
...
i managed stripping to ":" but i can't write them side by side in a list..
expected output is=
["manname1","manname2","manname3"...]
however it is:
["manname1"]
["manname2"]
["manname3"]
how can i do it as in the expected output.. thanx in advance :)
this is my sample file..
Ant Man: a, b
Frodo: x,y
Star : s, d
Thor: r, t
Spy: p,u
ant man,frodo,star... is the men mame.. and what i want to append a list..
Maybe create another list for example names and instead of printing the element on each iteration append it to this list. And then print the list after the loop is over.
j=0
women_names = []
while j < 5:
. . .
women_names.append(element_women)
j += 1
print women_names
As a general approach, instead of print use
import sys
sys.stdout.write(element)
sys.stdout.write(element_women)
which does not add newlines at the end.
In Python 3 note
print(element, end="")
print(element_women, end="")
In case the input does not show immediately (large buffer), consider respectively
sys.stdout.flush()
and
print(element, end="", flush=True)
try to use ','
print element,
print element_women
example:
print 'a',
print 'b'
output
a b

How to properly use the print function

while index < len(diecount):
print(index)
for number in range(diecount[index]):
print('*')
index+=1
print("")
At the moment i am getting
1
**
2
3
**
i want the output to be
1 **
2
3 **
A more Pythonic way to write this:
for index, count in enumerate(diecount[1:], start=1):
print(index, '*' * count)
(Manually controlling loop indexes in a while is usually a sign you're trying to write C code in Python).
Each print function appends a newline at the end of whatever it currently prints.
You can append a space instead of newline after the first print using the 2nd argument:
print(index, end = " ")

Print new output on same line [duplicate]

This question already has answers here:
Print in one line dynamically [duplicate]
(22 answers)
Closed 6 years ago.
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
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.
* 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
Similar to what has been suggested, you can do:
print(i, end=',')
Output: 0,1,2,3,
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="")
You can do something such as:
>>> print(''.join(map(str,range(1,11))))
12345678910
>>> 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.
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

Categories