Python Practice › String Programs › Program 58

Random binary string

EasyString Programs · 58 of 106

Write a Python program to generate a random binary string of a given length.

Advertisement
Input
8
Output
00110011

Approach

  1. Pick “0” or “1” for each position.

Solution

Python
import random random.seed(3)n = 8print("".join(random.choice("01") for _ in range(n)))
Output
00110011

Line by line

Line 3

The seed makes the output repeatable; remove it for a new string each run.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More string programs

← All 106 String Programs