-2
def rand_gen1():
    import random
    for i in range(8):
        print random.choice('0123456789abcdefghijklmnopqrstuvwxyz')

The above piece of code prints a string of 8 random chars or ints or both vertically. I need it to print like 'abcd123b' i.e. horizontally.

What changes do I need to make ?

pjs
  • 18,696
  • 4
  • 27
  • 56
YAsh rAj
  • 85
  • 1
  • 6
  • @khelwood It would be better to concatenate though instead of printing in every iteration as SumnerEvans proposes. – Ma0 Aug 23 '17 at 14:56

4 Answers4

5

Or like that (+ for Richard Neumann for importing from string):

import random
from string import ascii_lowercase, digits

def rand_gen3():
    print(''.join(random.choice(ascii_lowercase + digits) for _ in range(8)))

rand_gen3()
damisan
  • 1,037
  • 6
  • 17
2

You need to store the random choices in a string and then print the string:

import random

def rand_gen1():
    rand_str = ''
    for i in range(8):
        rand_str += random.choice('0123456789abcdefghijklmnopqrstuvwxyz')
    print rand_str

Each print statment creates a new line.

Sumner Evans
  • 8,951
  • 5
  • 30
  • 47
2
from random import choice
from string import ascii_lowercase, digits


def rand_gen(length=8, pool=digits+ascii_lowercase):

    return ''.join(choice(pool) for _ in range(length))


print rand_gen()
Richard Neumann
  • 2,986
  • 2
  • 25
  • 50
1

Right now you're printing out everything on its own new line by using print. You can make these all into one string by storing the values in a string variable.

import random
def rand_gen1():
    output = ""
    for i in range(8):
        output += random.choice('0123456789abcdefghijklmnopqrstuvwxyz')
    print output
Davy M
  • 1,697
  • 4
  • 20
  • 27