HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonModerate

Creating a string of random characters

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
creatingrandomcharactersstring

Problem

I'm generating domains with random names. I used the map function because it packages the results into a list which I can then join() into a string but the way I used the lambda function could be confusing to people reading this later.

def generateHost():
  charSet = 'abcdefghijklmnopqrstuvwxyz1234567890'
  minLength = 5
  maxLength = 30
  length = random.randint(minLength, maxLength)

  return ''.join(map(lambda unused : random.choice(charSet), range(length)))+".com"


This function calls generateHost() 'size' times and creates an array of hosts. I could write it like the above but it would be the same problem. I wrote it with a for loop which I'm still not satisfied with.

def generateHostList(size):
  result = []
  for i in range(size):
    result += [generateHost()]
  return result

Solution

The answer to this question suggests the following:

''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))


It's close to your solution, but avoids having to type out the whole alphabet by using predefined values and avoids the use of map() and lambda.

Code Snippets

''.join(random.choice(string.ascii_lowercase + string.digits) for _ in range(length))

Context

StackExchange Code Review Q#47529, answer score: 12

Revisions (0)

No revisions yet.