我想创建一个包含 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)
当然,这并没有奏效。你们能帮帮我吗? :)
最佳答案
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'
关于string - 使用列表的字符串/元素为 random.sample 提供范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900698/