How to generate all possible strings in python?

前端 未结 2 1026
北荒
北荒 2020-12-16 20:23

My goal is to be able to generate all possible strings (Letters and numbers) of length x and be able to activate a block of code for each one. (like an iterator) The only pr

相关标签:
2条回答
  • 2020-12-16 20:48

    Use itertools.product():

    >>> import itertools
    >>> map(''.join, itertools.product('ABC', repeat=3))
    ['AAA', 'AAB', 'AAC', 'ABA', 'ABB', 'ABC', 'ACA', 'ACB', 'ACC', 'BAA', 'BAB', 'BAC', 'BBA', 'BBB', 'BBC', 'BCA', 'BCB', 'BCC', 'CAA', 'CAB', 'CAC', 'CBA', 'CBB', 'CBC', 'CCA', 'CCB', 'CCC']
    

    Note that creating a list containing all combinations is very inefficient for longer strings - iterate over them instead:

    for string in itertools.imap(''.join, itertools.product('ABC', repeat=3)):
        print string
    

    To get all characters and numbers use string.uppercase + string.lowercase + string.digits.

    0 讨论(0)
  • 2020-12-16 20:55

    Use itertools.product() if you want letters to repeat:

    >>> from itertools import product
    >>> from string import ascii_uppercase
    >>> for combo in product(ascii_uppercase, repeat=3):
    ...     print ''.join(combo)
    ...
    AAA
    AAB
    ...
    ZZY
    ZZZ
    

    itertools.combinations() and itertools.permutations() are not the correct tools for your job.

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