>>> range(4) # range create a list of 'n' numbers[0, 1, 2, 3]>>> ['elem' for _ in range(4)] # we use range to create 4 times 'elem'['elem', 'elem', 'elem', 'elem']
因此random.choice(chars) for _ in range(size)实际上是在创建size字符的序列。从chars中随机选择的字符:
>>> [random.choice('abcde') for _ in range(3)]['a', 'b', 'b']>>> [random.choice('abcde') for _ in range(3)]['e', 'b', 'e']>>> [random.choice('abcde') for _ in range(3)]['d', 'a', 'c']
然后我们用一个空字符串连接它们,这样序列就变成了一个字符串:
>>> ''.join(['a', 'b', 'b'])'abb'>>> [random.choice('abcde') for _ in range(3)]['d', 'c', 'b']>>> ''.join(random.choice('abcde') for _ in range(3))'dac'
from os import urandomfrom itertools import islice, imap, repeatimport string
def rand_string(length=5):chars = set(string.ascii_uppercase + string.digits)char_gen = (c for c in imap(urandom, repeat(1)) if c in chars)return ''.join(islice(char_gen, None, length))
# must be length 32 -- 5 bits -- the question didn't specify using the full set# of uppercase letters ;)_ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
def generate_with_randbits(size=32):def chop(x):while x:yield x & 31x = x >> 5return ''.join(_ALPHABET[x] for x in chop(random.getrandbits(size * 5))).ljust(size, 'A')
import uuiduuid.uuid4() #uuid4 => full random uuid# Outputs something like: UUID('0172fc9a-1dac-4414-b88d-6b9a6feb91ea')
如果你需要你的格式(例如,“6U1S75”),你可以这样做:
import uuid
def my_random_string(string_length=10):"""Returns a random string of length string_length."""random = str(uuid.uuid4()) # Convert UUID format to a Python string.random = random.upper() # Make all characters uppercase.random = random.replace("-","") # Remove the UUID '-'.return random[0:string_length] # Return the random string.
print(my_random_string(6)) # For example, D9E50C
>>> import random>>> str = []>>> chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'>>> num = int(raw_input('How long do you want the string to be? '))How long do you want the string to be? 10>>> for k in range(1, num+1):... str.append(random.choice(chars))...>>> str = "".join(str)>>> str'tm2JUQ04CK'
from itertools import imap, starmap, islice, repeatfrom functools import partialfrom string import letters, digits, joinfrom random import choice
join_chars = partial(join, sep='')identity = lambda o: o
def irand_seqs(symbols=join_chars((letters, digits)), length=6, join=join_chars, select=choice, breakup=islice):""" Generates an indefinite sequence of joined random symbols each of a specific length:param symbols: symbols to select,[defaults to string.letters + string.digits, digits 0 - 9, lower and upper case English letters.]:param length: the length of each sequence,[defaults to 6]:param join: method used to join selected symbol,[defaults to ''.join generating a string.]:param select: method used to select a random element from the giving population.[defaults to random.choice, which selects a single element randomly]:return: indefinite iterator generating random sequences of giving [:param length]>>> from tools import irand_seqs>>> strings = irand_seqs()>>> a = next(strings)>>> assert isinstance(a, (str, unicode))>>> assert len(a) == 6>>> assert next(strings) != next(strings)"""return imap(join, starmap(breakup, repeat((imap(select, repeat(symbols)), None, length))))
import stringfrom random import *characters = string.ascii_letters + string.punctuation + string.digitspassword = "".join(choice(characters) for x in range(randint(8, 16)))print password
import randomq=2o=1list =[r'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','s','0','1','2','3','4','5','6','7','8','9','0']while(q>o):print("")
for i in range(1,128):x=random.choice(list)print(x,end="")
import string, randomlower = string.ascii_lowercaseupper = string.ascii_uppercasedigits = string.digitsspecial = '!"£$%^&*.,@#/?'
def rand_pass(l=4, u=4, d=4, s=4):p = [][p.append(random.choice(lower)) for x in range(l)][p.append(random.choice(upper)) for x in range(u)][p.append(random.choice(digits)) for x in range(d)][p.append(random.choice(special)) for x in range(s)]random.shuffle(p)return "".join(p)
print(rand_pass())# @5U,@A4yIZvnp%51
>>> from random import choices>>> from string import ascii_uppercase, digits
>>> population = ascii_uppercase + digits>>> str.join('', choices(population, k=6))'6JWF1H'
#!/usr/bin/env python
from typing import Generatorfrom random import SystemRandom as RNDfrom string import ascii_uppercase, digits
def string_generator(size: int = 2, amount: int = 1) -> Generator[str, None, None]:"""Return x random strings of a fixed length.
:param size: string length, defaults to 1:type size: int, optional:param amount: amount of random strings to generate, defaults to 1:type amount: int, optional:yield: Yield composed random string if unique:rtype: Generator[str, None, None]"""if size < 2:print('Since the string must contain letters and numbers,','its size must be at least two characters',)returnCHARS = list(ascii_uppercase + digits)LIMIT = len(CHARS) ** sizecount, check, string = 0, set(), ''while LIMIT > count < amount:while 1:string = ''.join(RND().choices(CHARS, k=size))if not (string.isalpha() or string.isnumeric()):breakif string not in check:check.add(string)yield stringcount += 1
for my_count, my_string in enumerate(string_generator(6, 20)):print(my_count, my_string)
import stringimport random
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):return ''.join(random.choice(chars) for _ in range(size))
moja_lista = []for a in range(20):moja_lista.append(id_generator(3, "3etrY"))