我想要创建一个变量,其中包含有3-7个随机字母的名称。(名字是否不正确并不重要)。我知道如何包含3个字母,但我只是不知道如何使用字母(string/list)处理范围。到目前为止,这是我的代码:
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)当然,这没什么用。你们能帮帮我吗?
发布于 2017-10-24 01:55:13
random.sample(ABC, 3)返回一个列表。如下所示
>>> random.sample(ABC, 3)
['q', 'h', 'x']可以使用join方法将其转换为字符串。
>>> a = random.sample(ABC, 3)
>>> a
['q', 'h', 'x']
>>>''.join(a)
'qhx'编辑:您甚至可以使用随机模块的朗朗在3到7之间选择数字。
>>> a = random.sample(ABC, random.randint(3,7))
>>> ''.join(a)
'bvt'
>>> b = random.sample(ABC, random.randint(3,7))
>>> ''.join(b)
'fycu'发布于 2017-10-24 01:52:28
现在明白你的问题了:
import random
ABC = ['A', 'Á', 'B', 'C'...]
letter_random = random.randint(3,7)
word = random.sample(ABC, letter_random)
print(''.join(word))https://stackoverflow.com/questions/46900698
复制相似问题