Home > Software design >  Generate Random String as String, not List
Generate Random String as String, not List

Time:01-22

from string import ascii_uppercase, digits
import string
import random


def generatestr():
    str0 = random.sample(digits   ascii_uppercase,2)   random.sample(ascii_uppercase,1)   random.sample(digits   ascii_uppercase,2)
    str1 = random.sample(digits   ascii_uppercase,5)
    str2 = random.sample(digits   ascii_uppercase,3)   random.sample(ascii_uppercase,1)   random.sample(digits   ascii_uppercase,1)
    str3 = random.sample(digits   ascii_uppercase,5)
    str4 = random.sample(digits   ascii_uppercase,4)
    key = str(str0)   "-"   str(str1)   "-"   str(str2)   "-"   str(str3)   "-"   str(str4)   "Z"
    return ''.join(key)

    

print(generatestr())

['H', 'J', 'U', 'V', '8']-['6', '4', '5', 'Z', '0']-['L', '8', '7', 'D', 'Q']-['9', 'P', 'F', 'T', 'B']-['M', '8', 'G', 'V']Z

Expected output: ABCDE-ABCDE-ABCDE-ABCDE-ABCDZ

CodePudding user response:

Random.sample returns a list. When you use str(str0) then you change a list to a string which outputs: ['H', 'J', 'U', 'V', '8']

In order to get expected output, you have to change a line to:

key = "".join(str0)   "-"   "".join(str1)   "-"   "".join(str2)   "-"   "".join(str3)   "-"   "".join(str4)   "Z"

CodePudding user response:

Solution:

    key = ''.join(str0)   "-"   ''.join(str1)   "-"   ''.join(str2)   "-"   ''.join(str3)   "-"   ''.join(str4)   "Z"
    return key

CodePudding user response:

str when used on a collection typically gives a string that looks like an inline representation of the collection, hence

str([1,2,3])

outputs

'[1, 2, 3]'

To give a string representation of a list the way you want it, you want to join the items of the list. my_string.join, as you've already noticed, applies the str function to each item of a list, concatenates all the results, separating them using the value of the string my_string, then returns the result. Hence

''.join([1,2,3])

outputs

'123'

So this is what you want:

def generatestr():
    rands = []
    rands.append(random.sample(digits   ascii_uppercase,2)   random.sample(ascii_uppercase,1)   random.sample(digits   ascii_uppercase,2))
    rands.append(random.sample(digits   ascii_uppercase,5))
    rands.append(random.sample(digits   ascii_uppercase,3)   random.sample(ascii_uppercase,1)   random.sample(digits   ascii_uppercase,1))
    rands.append(random.sample(digits   ascii_uppercase,5))
    rands.append(random.sample(digits   ascii_uppercase,4))
    return '-'.join([''.join(rand_list) for rand_list in rands])
  • Related