解决方法
有几种方法,最简单的方法:
>>> import string >>> import random >>> string.ascii_letters[:random.randint(1,50)].title() 'Abcdefghijklmnopq' >>> string.ascii_letters[:random.randint(1,50)].title() 'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq' >>> string.ascii_letters[:random.randint(1,50)].title() 'Abcdefghijklmnopqrs'
或者你可以使用itertools:
>>> import string >>> import random >>> from itertools import islice,cycle >>> def randstr(): ... return ''.join(islice(cycle(string.ascii_lowercase),... random.randint(1,50))).title() ... >>> randstr() 'Abcdefghijklmnopq' >>> randstr() 'Abcdefghijklmnopqrstuvwxyzabcdefghijklmnopq' >>> randstr() 'Abcdefghijklmnopqrs'