Random string generation with upper case letters and digits

前端 未结 30 3072
逝去的感伤
逝去的感伤 2020-11-22 02:51

I want to generate a string of size N.

It should be made up of numbers and uppercase English letters such as:

  • 6U1S75
  • 4Z4UKK
  • U911K4
相关标签:
30条回答
  • 2020-11-22 02:55

    If you want an easy-to-use but highly customisable key generator, use key-generator pypi package.

    Here is the GitHub repo where you can find the complete documentation.

    You can customise it to give a string jist like you want with many more options. Here's an example:

    from key_generator.key_generator import generate
    
    custom_key = generate(2, ['-', ':'], 3, 10, type_of_value = 'char', capital = 'mix', seed = 17).get_key()
    print(custom_key)  # ZLFdHXIUe-ekwJCu
    

    Hope this helps :)

    Disclaimer: This uses the key-generator library which I made.

    0 讨论(0)
  • 2020-11-22 02:56

    I thought no one had answered this yet lol! But hey, here's my own go at it:

    import random
    
    def random_alphanumeric(limit):
        #ascii alphabet of all alphanumerals
        r = (range(48, 58) + range(65, 91) + range(97, 123))
        random.shuffle(r)
        return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))], "")
    
    0 讨论(0)
  • 2020-11-22 02:57

    For those of you who enjoy functional python:

    from itertools import imap, starmap, islice, repeat
    from functools import partial
    from string import letters, digits, join
    from 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))))
    

    It generates an indefinite [infinite] iterator, of joined random sequences, by first generating an indefinite sequence of randomly selected symbol from the giving pool, then breaking this sequence into length parts which is then joined, it should work with any sequence that supports getitem, by default it simply generates a random sequence of alpha numeric letters, though you can easily modify to generate other things:

    for example to generate random tuples of digits:

    >>> irand_tuples = irand_seqs(xrange(10), join=tuple)
    >>> next(irand_tuples)
    (0, 5, 5, 7, 2, 8)
    >>> next(irand_tuples)
    (3, 2, 2, 0, 3, 1)
    

    if you don't want to use next for generation you can simply make it callable:

    >>> irand_tuples = irand_seqs(xrange(10), join=tuple)
    >>> make_rand_tuples = partial(next, irand_tuples) 
    >>> make_rand_tuples()
    (1, 6, 2, 8, 1, 9)
    

    if you want to generate the sequence on the fly simply set join to identity.

    >>> irand_tuples = irand_seqs(xrange(10), join=identity)
    >>> selections = next(irand_tuples)
    >>> next(selections)
    8
    >>> list(selections)
    [6, 3, 8, 2, 2]
    

    As others have mentioned if you need more security then set the appropriate select function:

    >>> from random import SystemRandom
    >>> rand_strs = irand_seqs(select=SystemRandom().choice)
    'QsaDxQ'
    

    the default selector is choice which may select the same symbol multiple times for each chunk, if instead you'd want the same member selected at most once for each chunk then, one possible usage:

    >>> from random import sample
    >>> irand_samples = irand_seqs(xrange(10), length=1, join=next, select=lambda pool: sample(pool, 6))
    >>> next(irand_samples)
    [0, 9, 2, 3, 1, 6]
    

    we use sample as our selector, to do the complete selection, so the chunks are actually length 1, and to join we simply call next which fetches the next completely generated chunk, granted this example seems a bit cumbersome and it is ...

    0 讨论(0)
  • 2020-11-22 02:58

    A simple one:

    import string
    import random
    character = string.lowercase + string.uppercase + string.digits + string.punctuation
    char_len = len(character)
    # you can specify your password length here
    pass_len = random.randint(10,20)
    password = ''
    for x in range(pass_len):
        password = password + character[random.randint(0,char_len-1)]
    print password
    
    0 讨论(0)
  • 2020-11-22 02:59

    I have gone though almost all of the answers but none of them looks easier. I would suggest you to try the passgen library which is generally used to create random passwords.

    You can generate random strings of your choice of length, punctuation, digits, letters and case.

    Here's the code for your case:

    from passgen import passgen
    string_length = int(input())
    random_string = passgen(length=string_length, punctuation=False, digits=True, letters=True, case='upper')
    
    0 讨论(0)
  • 2020-11-22 03:00

    A faster, easier and more flexible way to do this is to use the strgen module (pip install StringGenerator).

    Generate a 6-character random string with upper case letters and digits:

    >>> from strgen import StringGenerator as SG
    >>> SG("[\u\d]{6}").render()
    u'YZI2CI'
    

    Get a unique list:

    >>> SG("[\l\d]{10}").render_list(5,unique=True)
    [u'xqqtmi1pOk', u'zmkWdUr63O', u'PGaGcPHrX2', u'6RZiUbkk2i', u'j9eIeeWgEF']
    

    Guarantee one "special" character in the string:

    >>> SG("[\l\d]{10}&[\p]").render()
    u'jaYI0bcPG*0'
    

    A random HTML color:

    >>> SG("#[\h]{6}").render()
    u'#CEdFCa'
    

    etc.

    We need to be aware that this:

    ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(N))
    

    might not have a digit (or uppercase character) in it.

    strgen is faster in developer-time than any of the above solutions. The solution from Ignacio is the fastest run-time performing and is the right answer using the Python Standard Library. But you will hardly ever use it in that form. You will want to use SystemRandom (or fallback if not available), make sure required character sets are represented, use unicode (or not), make sure successive invocations produce a unique string, use a subset of one of the string module character classes, etc. This all requires lots more code than in the answers provided. The various attempts to generalize a solution all have limitations that strgen solves with greater brevity and expressive power using a simple template language.

    It's on PyPI:

    pip install StringGenerator
    

    Disclosure: I'm the author of the strgen module.

    0 讨论(0)
提交回复
热议问题