-3

I have a string 'ABCDEF', I would like 4 unique characters to be generated randomly every time I run the program.

The result should give something like:

BDAF

EDCB

CAFE

...

I could use random.sample but it would require a list to be used instead, are there ways of achieving the same result using a string?

Sijie
  • 11
  • 2
  • 6
    `random.sample` works perfectly fine with strings. And you can easily convert the list it returns to a string, too. – Aran-Fey Sep 07 '18 at 07:38
  • Possible duplicate of [Convert a list of characters into a string](https://stackoverflow.com/questions/4481724/convert-a-list-of-characters-into-a-string) – Nouman Sep 07 '18 at 08:04

4 Answers4

2

You can use the functions provided by Python's random module. Use random.sample to extract a random set of characters from the string and then join them:

import random
source = "ABCDEFG"
result = "".join(random.sample(source, 4))
Nouman
  • 6,947
  • 7
  • 32
  • 60
Sven Rusch
  • 1,357
  • 11
  • 17
1

You can indeed use random.sample; it'll give you a list, but it's easy enough to join the resulting list into a string:

result = ''.join(random.sample("ABCDEF", 4))
OliverRadini
  • 6,238
  • 1
  • 21
  • 46
0

You can do this using random then join your resulting list with '' to create a string:

import random
c = "ABCDEF"
''.join(random.sample(c, 4))

For input, you can use a string as in Python a string is also a list (list of characters)

RoyaumeIX
  • 1,947
  • 4
  • 13
  • 37
-1

There are 3 solutions (and probably 100 more):

  1. 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,

  2. 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),

  3. 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))
Andrea
  • 249
  • 2
  • 7