Randomly pick characters to make a word

3504 views python
5

lets say I want to make my name goofy with different variations randomly.

i have the name BoA - i could do something like this right?

import random
list1=['B', '13', 'ß']
list2=['o', 'ø', 'Ö']
list3=['A', 'Ä', 'Á']
random1=random.randint(0,3)
random2=random.randint(0,3)
random3=random.randint(0,3)
print(list1[random1]+ list2[random2]+ list3[random3])

>> BøÁ

is there an easier way for me to do this? I just want to know what all my possibilities are. Also, I do get this error. It works fine if its regular characters, so i'm not sure how to fix that.

File "main.py", line 2
SyntaxError: Non-ASCII character '\xc3' in file main.py on line 2, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Thanks !

answered question

2 Answers

10

You could use choice:

# coding=utf-8
import random

list1 = ['B', '13', 'ß']
list2 = ['o', 'ø', 'Ö']
list3 = ['A', 'Ä', 'Á']
random1 = random.choice(list1)
random2 = random.choice(list2)
random3 = random.choice(list3)
print(random1 + random2 + random3)

Output

13oÄ

Also as mentioned by the error you need to define the source encoding: # coding=utf-8.

posted this
11

You could use random.choice, if you want to make longer words this approach won't really be reasonable though (imagine having to create 9 different variables for a word length 9, etc.), so I would use a for loop:

lists = [['B', '13', 'ß'],
         ['o', 'ø', 'Ö'],
         ['A', 'Ä', 'Á']]
word = ''
for lst in lists:
    word += random.choice(lst)
print(word)

posted this

Have an answer?

JD

Please login first before posting an answer.