使用列表的字符串/元素为random.sample提供范围

时间:2017-10-24 01:09:11

标签: string python-3.x random range sample

我想创建一个包含3-7个随机字母的名称的变量。 (如果名称不正确,则无关紧要)。我知道怎么做才能包含3个字母,但我不知道如何用字母处理范围(字符串/列表)。到目前为止,这是我的代码:

import random
ABC = ['A', 'Á', 'B', 'C'... just imagine every single letter of the Hungarian alphabet as a list]
name = random.sample(ABC, 3)

我试着这样做:

name = random.sample(ABC, 3) or random.sample(ABC, 4)

但当然没有用。你能帮帮我吗? :)

2 个答案:

答案 0 :(得分:1)

random.sample(ABC, 3)返回一个列表。如下

>>> random.sample(ABC, 3)
['q', 'h', 'x']

您可以使用join方法

将其转换为字符串
>>> a = random.sample(ABC, 3)
>>> a 
['q', 'h', 'x']
>>>''.join(a)
'qhx'

编辑:您甚至可以使用随机模块的randint来选择3到7之间的数字

>>> a = random.sample(ABC, random.randint(3,7))
>>> ''.join(a)
'bvt'
>>> b = random.sample(ABC, random.randint(3,7))
>>> ''.join(b)
'fycu'

答案 1 :(得分:0)

现在明白你的问题:

import random
ABC = ['A', 'Á', 'B', 'C'...]
letter_random = random.randint(3,7)
word = random.sample(ABC, letter_random)
print(''.join(word))