Generate alphanumeric strings sequentially

前端 未结 5 2078
我寻月下人不归
我寻月下人不归 2020-12-25 08:38

I\'m trying to create a loop to generate and print strings as follows:

  1. Alphanumeric characters only:
  2. 0-9 are before A-Z, which are before a-z,
5条回答
  •  情书的邮戳
    2020-12-25 09:44

    This seems like the simplest solution to me:

    from string import digits, ascii_uppercase, ascii_lowercase
    
    chars = digits + ascii_uppercase + ascii_lowercase
    all_str = [''.join([a]) for a in chars] \
            + [''.join([a,b]) for a in chars for b in chars] \
            + [''.join([a,b,c]) for a in chars for b in chars for c in chars] \
            + [''.join([a,b,c,d]) for a in chars for b in chars for c in chars for d in chars]
    
    print(all_str)
    print("Number of strings:", len(all_str))
    

    Example for strings with maximum 2 characters.

    Of course, there may be a way to generalize to any max number of characters per string, but since you have a specific need for strings up to 4 characters, it's fine.

提交回复
热议问题