218

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'
4
  • 30
    Leave "in one line of code" to code obfuscation contests. When the solution to a problem is naturally written as one line, it will be; otherwise it shouldn't be. Using it as a goal of its own is a guaranteed path to nasty code. Commented Sep 14, 2009 at 22:32
  • 4
    Unless, of course, this is homework. In which case, leave the "in one line of code" but be honest and include the [homework] tag. Commented Sep 15, 2009 at 0:12
  • 6
    It's actually not a homework question, I just needed a string of n length in my test scripts. I forgot that in Python, a char can be multiplied by n where n is a positive integer to achieve what I want. Commented Sep 15, 2009 at 1:08
  • refer this stackoverflow.com/a/3391106/3779480 Commented Jun 16, 2015 at 11:24

8 Answers 8

432

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))
Sign up to request clarification or add additional context in comments.

Comments

15

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

2 Comments

In Python 3.1.1, it's string.ascii_lowercase actually.
Yep, python 3 removed .lowercase (ascii_lowercase is in recent Python 2's as well as in Python 3).
10

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'

Comments

6

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'

3 Comments

You can fit anything into one-line, eh? Quite a claim, re: Python :)
Gregg: Python allows semicolons as statement delimiters, so you can put an entire program on one line if desired.
You can't do arbitrary flow control with semicolons though. Nested loops for example.
5

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.

Comments

4

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

>>> 'a'*5

'aaaaa'

Comments

0

You can use string formatting to ensure a string has exactly n characters. For example, let's say you have a decimal portion of a number that you want to parse with some specific precision:

>>> n = 3
>>> s = "12"
>>> f"{s:0<{n}.{n}}"
120
>>> s = "1234"
>>> f"{s:0<{n}.{n}}"
123

The padding character is '0' in this case, but you can set it to whatever value you want.

Comments

0

Assuming - the original request is about formatting of result-string, where the essential part of the string is known, has arbitrary length and should be extended with some additional symbols (e.g. spaces) to get same length of n characters. In this case the solution might look like this:

n = 10
items = ['1', 777, 'my str', '1000', '', 0] # example of several items reflecting different string-length
for i in items:
    print( ' '*(n-len(str(i))) + str(i) ) # string-extension as a single-line

However if original ("known") strings might have length bigger than n - the result length will be also bigger than n. In such case pre-processing might be needed to get maximal length of original strings and adapt the n correspondingly. Implementing of such pre-processing in a single-line could be quite ugly to understand and maintain:

n = 10
items = ['1', 777, 'my str', '1000', '', 0, '012345678901'] # example of several items reflecting different string-length
for i in items:
    print( ' '*(max([len(str(k)) for k in items]+[n])-len(str(i))) + str(i) ) # string-extension as a single-line with considering case when items might have string-length bigger than n

Therefore - as already proposed by other replies and comments - a single-line solution should be only used when it's meaningful, easy to implement and clear for others. By all other cases - either implement it at several lines, or - if explicitly needed as a single line solution (e.g. by automatic re-factoring) - define a separated function for required functionality and call it within single line.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.