0

I built a basic script that shows a string of random binary values (0 and 1) i times through a for loop.

It doesn't bother me, but in every loop, it automatically creates a new line and then prints the binary value

Example of the output:

1
0
1
1
0
...

Why is that? And how can I display the values in a "newlineless" string (without spaces too)?

Like 001010001011010111010, as an example.

Here's the code:


i = 20 #number of random binary to be shown

for x in range(i):
    bin = randint(0, 1)
    print(bin)
Kiko
  • 45
  • 7

3 Answers3

2
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

it default end with a newline charater. if you want to have something else, you can do print('hi', end=something) where something is the string you want.
in you case something = ""

  • Thanks! I read a bit of the python docs but never found these arguments in the print function. Can I ask, what is the `file = sys.stdout` in the arguments? – Kiko Apr 16 '22 at 10:21
  • @Kiko kinda complicated if you really want to know what it is. generally saying the terminal(or whereever you run the code, its just a console) will displace text inside a file. a general file the console displaying is sys.stdout (which stand for system stand output). – Lawrence Ho Chun Kit Apr 17 '22 at 10:25
  • @Kiko so if you now want to save the text to a special file, let's say 'test.txt'. you could do `print('hi', file= 'test.txt')` and then you will save the string in the path instead of displaying on the console. – Lawrence Ho Chun Kit Apr 17 '22 at 10:26
  • A bit late, but that's really really handy! My next step for this script was to save output in a file, but creating a file, saving outout on a variable, copying the variable to the file, sounded way too complicated for such a simple thing. TIL! – Kiko Apr 23 '22 at 20:22
1

In python, a line break is added by default every time you call print. If you instead would like to print something else you can customise this behaviour by changing end e.g. print(str, end=" ") would probably work for you.

1

You need to specify the end parameter -- in this case, it's the empty string:

from random import randint

i = 20 #number of random binary to be shown
for x in range(i):
    val = randint(0, 1)
    print(val, end='', flush=True)

There are two other things worth noting:

  1. Don't use bin as a variable name -- it shadows a built-in.
  2. Standard output is buffered, which means that what you write to the console won't appear until a newline is written or the buffer is explicitly flushed. In this case, we pass flush=True so that our output appears on the console immediately.
BrokenBenchmark
  • 18,126
  • 7
  • 21
  • 33