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 one answer to achieve this problem with the existing Python library? For example, I need a string of 10 letters:

string_val = 'abcdefghij' 
+90
python string
Sep 14 '09 at 21:26
source share
6 answers

To simply repeat the same letter 10 times:

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

And if you need something more complex, like n random lowercase letters, it is 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)) 
+208
Sep 14 '09 at 21:28
source share

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

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

+9
Sep 14 '09 at 21:28
source share

if you just need letters:

  'a'*10 # gives 'aaaaaaaaaa' 

if you need consecutive letters (up to 26):

  ''.join(['%c' % x for x in range(97, 97+10)]) # gives 'abcdefghij' 
+4
Sep 14 '09 at 21:31
source share

Why "single line"? You can put anything on one line.

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

 >>> mkstring = lambda(x): "".join(map(chr, (ord('a')+(y%26) for y in range(x)))) >>> mkstring(10) 'abcdefghij' >>> mkstring(30) 'abcdefghijklmnopqrstuvwxyzabcd' 
+3
Sep 14 '09 at 21:30
source share

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

 >>> 'a'*5 'aaaaa' 
+2
Sep 14 '09 at 21:29
source share

This may not be a bit on this question, but for those who are interested in the randomness of the generated string, my answer would be this:

 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 the random.py source for a deeper understanding.

+1
Jan 17 '14 at 18:12
source share



All Articles