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


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 letters:

string_val = 'abcdefghij'
5/4/2010 12:44:43 AM

Accepted Answer

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))
1/1/2019 4:25:41 AM

The first ten lowercase letters are string.lowercase[:10] (if you have imported the standard library module string previously, of course;-).

Other ways to "make a string of 10 characters": 'x'*10 (all the ten characters will be lowercase xs;-), ''.join(chr(ord('a')+i) for i in xrange(10)) (the first ten lowercase letters again), etc, etc;-).

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow