Defframe
Defframe

Reputation: 21

How to generate a string of random symbols from a string using python's random module?

Ok, so i want the python's random module to choose 10 random symbols from a string and print it into the console. random.choices returns a list but i want a string like "1jF7Ud7oVj". How can i do this?

Upvotes: 1

Views: 91

Answers (4)

theX
theX

Reputation: 1134

You can use ''.join(list_name) to conjoin items in a list together

Upvotes: 0

Roshin Raphel
Roshin Raphel

Reputation: 2709

Use the string and random modules, this will not start from a seed value :

import string 
import random 
st = ''.join(random.choices(string.ascii_lowercase + string.digits, k = 10)) 
print("The generated random string :",str(st)) 

You can use :

st = ''.join(random.choices(string.ascii_uppercase + string.digits, k = 10)) 

for upper case strings and remove + string.digits if no digits are required

Upvotes: 0

Tenshi
Tenshi

Reputation: 13

choice works exactly like choices without returning as a list

from random import choice
string="The day the earth stood still"
randoms=""
for i in range(10):
        randoms+=choice(string)
print(randoms)

Upvotes: 1

oranav
oranav

Reputation: 21

You can just wrap the list with ''.join(), for example:

>>> ''.join(random.choices('abcdef', k=10))
'befabfadee'

Upvotes: 2

Related Questions