In Python, how do I create a string of n characters in one line of code?

前端 未结 6 1327
梦毁少年i
梦毁少年i 2020-12-02 11:58

I need to generate a string with n characters in Python. Is there a one line answer to achieve this with the existing Python library? For instance, I need a string of 10 l

6条回答
  •  既然无缘
    2020-12-02 12:15

    This might be a little off the question, but for those interested in the randomness of the generated string, my answer would be:

    import os
    import string
    
    def _pwd_gen(size=16):
        chars = string.letters
        chars_len = len(chars)
        return str().join(chars[int(ord(c) / 256. * chars_len)] for c in os.urandom(size))
    

    See these answers and random.py's source for more insight.

提交回复
热议问题