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'
Jon Seigel
12.1k8 gold badges57 silver badges92 bronze badges
asked Sep 14, 2009 at 21:26
Thierry LamThierry Lam
43.9k40 gold badges115 silver badges144 bronze badges
4
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]]
answered Sep 14, 2009 at 21:28
Eli CourtwrightEli Courtwright
179k65 gold badges208 silver badges256 bronze badges
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 x
s;-], ''.join[chr[ord['a']+i] for i in xrange[10]]
[the first ten lowercase letters again], etc, etc;-].
answered Sep 14, 2009 at 21:28
Alex MartelliAlex Martelli
824k163 gold badges1202 silver badges1379 bronze badges
2
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'
answered Sep 14, 2009 at 21:31
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'
answered Sep 14, 2009 at 21:30
John MillikinJohn Millikin
193k39 gold badges211 silver badges222 bronze badges
3
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.
answered Jan 17, 2014 at 18:12
foudfoufoudfou
8566 silver badges11 bronze badges
If you can use repeated letters, you can use the *
operator:
>>> 'a'*5
'aaaaa'
answered Sep 14, 2009 at 21:29
FragsworthFragsworth
32k26 gold badges82 silver badges97 bronze badges