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

前端 未结 6 1338
梦毁少年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:26

    To simply repeat the same letter 10 times:

    string_val = "x" * 10  # gives you "xxxxxxxxxx"
    

    And if you want something more complex, like n random lowercase letters, it's still only one line of code (not counting the import statements and defining n):

    from random import choice
    from string import ascii_lowercase
    n = 10
    
    string_val = "".join(choice(ascii_lowercase) for i in range(n))
    

提交回复
热议问题