Reputation: 559
For clarification, I don't just only want a random letter word. I need the random numbers in my code later on also.
I made the following code which gives a random 7 letter word.
Here is the code:-
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
print value(key_num[0]) + value(key_num[1]) + value(key_num[2]) + value(key_num[3]) + value(key_num[4]) + value(key_num[5]) + value(key_num[6])
My question is there any better way to concatenate the word using the random numbers?
Upvotes: 0
Views: 1094
Reputation: 1342
You've tagged your question Python2.7. If you can use Python3 instead, you can use random.choices to make things rather simple:
from string import ascii_lowercase
from random import choices
print ("".join(choices(ascii_lowercase,k=7)))
If you're stuck in Python2, you can implement a (simplistic) random.choices
thus:
from random import choice
def choices(s,k=1):
return [choice(s) for _ in xrange(k)]
Upvotes: 1
Reputation: 46899
this is a way:
from random import randrange
from string import ascii_lowercase
def random_str(length=7):
return ''.join(ascii_lowercase[randrange(len(ascii_lowercase))] for _ in range(length))
ascii_lowercase
is just 'abcdefghijklmnopqrstuvwxyz'
; i select a random entry from that and join the single letters with str.join
.
...actually random.choice
is better suited for that. see this answer.
Upvotes: 0
Reputation: 3811
There are many different ways to solve this and also improve your code. You should definitely checkout str.join
and list comprehensions.
If you want to stick to your original code as much as possible, how about this basic solution:
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
# so far unchanged, here comes the new bit:
print ''.join(value(k) for k in key_num)
Upvotes: 1
Reputation: 114038
import string
word = "".join(random.choice(string.ascii_lowercase) for _ in range(string_length)]
Is how i would make a random string
Upvotes: 2
Reputation: 2344
You can achieve concatenation in a single for loop.
Try Below Code:
import random
key_num = []
for initial_num in range(7):
key_num.append(random.randrange(1,26))
def value(n):
return (chr(int(n) + 64))
final_string = ""
for i in range(7): # Range of Numbers you want
final_string += value(key_num[i]) # Concatenate random character
print final_string
Upvotes: 0