There are 3 solutions (and probably 100 more):
The"classic" for
method appending everyone of the N=4
letters to the same string and the choice
method of the random
module that picks one element among its arguments,
Using the join
method
to add in one time the elements generated by the choices
method of the random
module. The choices
method is very versatile and can be used with several arguments (official documentation),
Using the join
method
to add in one time the elements generated by the sample
method of the random
module. The sample(set,num)
method picks randomly num
elements in set
.
import random
N=4
source_string = 'ABCDEF
Method1
random_string_1=""
for it in range(0,N):
random_string_1 = random_string_1 + random.choice(source_string)
Method2
random_string_2 = "".join(random.choices(source_string, weights=None,
cum_weights=None, k=N))
Method3
random_string_3 = "".join(random.sample(source_string, N))