Home > database >  How to create random string using user-inputted characters (Python 3)
How to create random string using user-inputted characters (Python 3)

Time:09-04

My code looks like this:

char = input('Characters: ')
length = int(input('Length: '))

I want to make a length long string which uses randomly selected characters from the char variable. How can I do this?

CodePudding user response:

You can use random.choice to choose 1 random character for length times. Here are some potential answers: With for loops:

import random

chars = input("Characters: ")
length = int(input("Length: "))
result = ''
for _ in range(length):
    result  = random.choice(chars)

or with list comps:

import random

chars = input("Characters: ")
length = int(input("Length: "))
result = ''.join([random.choice(chars) for _ in range(length)])

You'll get the random string in result

CodePudding user response:

You can simply use choice from random library

import random
char = input('Characters: ')
list_array = [char for char in char]
length = int(input('Length: '))

my_str = ""
for i in range(length):
    my_str  = random.choice(char)
print(my_str)

CodePudding user response:

Assuming that the same character can appear several times in char but that the probability with which this character can appear in the generated string should be the same as for any other character, I would suggest to convert the inputted character string to a set (for uniqueness), then to a list, and then use the choice function from the random module in a loop for the desired number of times:

from random import choice
char = input('Characters: ')
char_list = list(set(char))
generated_string = ""
length = int(input('Length: '))
for i in range(length):
    generated_string  = choice(char_list)
print(generated_string)

CodePudding user response:

TL;DR

In one line, without the need for any for loop

import random
mylongstring=''.join(random.choices(char, k=length)) # If non-unique sampling is needed
mylongstring=''.join(random.sample(char, k=length)) # If Unique elements from string are required

Explanation

You can use random.choices with k equal to you string length. It extracts randomly k elements from your generating iterable element (and string is naturally a sequence of characters). Then you can join your new list. If you use random.sample instead, the sampling is performed uniquely (each character is extracted only once from your char)

The code is here (note that I fixed char and length just for easy testing purposes)

char = 'mystring'
length =  20

import random
mylonglist = random.choices(char, k=length)
mylongstring=''.join(mylonglist)

print(mylongstring)

# result printed: isngmgstssyinismnsrt

# for unique sampling
length=5
mylonglist = random.sample(char, k=length)
mylongstring=''.join(mylonglist)
print(mylongstring)
# printed: irtgs

Here you find the doc for random.choices and for random.sample

CodePudding user response:

Within the module random in numpy, the choice function allows you to manage the cases with and without replacement (in simple words, can the characters in char string be picked more than or only once?):

import numpy as np

my_string = "hello"

print(np.random.choice(list(my_string), 3, replace=False))

OUTPUT

lol

Note that, if replace=True, you can only request for a number of characters not greater than the length of my_string, otherwise a ValueError will be thrown:

ValueError: Cannot take a larger sample than population when 'replace=False'
  • Related