Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

string

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' 
like image 264
Thierry Lam Avatar asked Sep 14 '09 21:09

Thierry Lam


People also ask

How do I make an n string in Python?

To access the first n characters of a string in Python, we can use the subscript syntax [ ] by passing 0:n as an arguments to it. 0 is the starting position of an index. n is the number of characters we need to extract from the starting position (n is excluded).

How do I string a list of characters in Python?

To convert a string to list of characters in Python, use the list() method to typecast the string into a list. The list() constructor builds a list directly from an iterable, and since the string is iterable, you can construct a list from it.

How do you create a string of specific length in Python?

In Python, strings have a built-in method named ljust . The method lets you pad a string with characters up to a certain length. The ljust method means "left-justify"; this makes sense because your string will be to the left after adjustment up to the specified length.

How do you add characters to a string in Python?

Add a Character to a String in Python Using the + Operator The + operator can concatenate two strings or a string and a character and returns a new string in Python.


1 Answers

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)) 
like image 158
Eli Courtwright Avatar answered Oct 27 '22 22:10

Eli Courtwright