views:

524

answers:

5

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'
+6  A: 

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;-).

Alex Martelli
In Python 3.1.1, it's string.ascii_lowercase actually.
Lasse V. Karlsen
Yep, python 3 removed `.lowercase` (`ascii_lowercase` is in recent Python 2's as well as in Python 3).
Alex Martelli
+11  A: 

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 lowercase
n = 10

string_val = "".join(choice(lowercase) for i in range(n))
Eli Courtwright
A: 

If you can use repeated letters, you can use the * operator:

>>> 'a'*5

'aaaaa'
Fragsworth
+1  A: 

Why "one line"? You can fit anything onto one line.

Assuming you want them to start with 'a', and increment by one character each time (with wrapping > 26), here's a line:

>>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x))))
>>> mkstring(10)
'abcdefghij'
>>> mkstring(30)
'abcdefghijklmnopqrstuvwxyzabcd'
John Millikin
You can fit anything into one-line, eh? Quite a claim, re: Python :)
Gregg Lind
Gregg: Python allows semicolons as statement delimiters, so you can put an entire program on one line if desired.
John Millikin
You can't do arbitrary flow control with semicolons though. Nested loops for example.
recursive
A: 

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'
Peter