Python | First N letters string construction
Sometimes, rather than initializing the empty string, we need to initialize a string in a different way, vis., we may need to initialize a string with 1st N characters in English alphabets. This can have application in competitive Programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using join() + list comprehension
This task can be performed with the combination of the above functions. The join function can be used to join the string and list comprehension can perform the task of logic of adding N numbers.
# Python3 code to demonstrate # First N letters string construction # using join() + list comprehension # initializing N N = 15 # using join() + list comprehension # First N letters string construction res = ''.join(['% c' % x for x in range(97, 97 + N)]) # print result print("The string after construction : " + str(res)) |
The string after construction : abcdefghijklmno
Method #2 : Using ord() + join() + list comprehension
This is yet another way in which this task can be performed, the ord function performs the task of type casting of ascii number to a character, rest the technique is similar to above method.
# Python3 code to demonstrate # First N letters string construction # using join() + list comprehension + ord() # initializing N N = 15 # using join() + list comprehension + ord() # First N letters string construction res = ''.join(chr(ord('a')+i) for i in range(N)) # print result print("The string after construction : " + str(res)) |
The string after construction : abcdefghijklmno
Recommended Posts:
- Python | Insert value after each k letters in given list of string
- Python | Ways to sort letters of string alphabetically
- Python | Remove all characters except letters and numbers
- Regex in Python to put spaces between words starting with capital letters
- Python regex to find sequences of one upper case letter followed by lower case letters
- String slicing in Python to check if a string can become empty by recursive deletion
- Python | Check if given string can be formed by concatenating string elements of list
- Python | Merge Tuple String List values to String
- Python | Sorting string using order defined by another string
- Python | Check if string ends with any string in given list
- String slicing in Python to rotate a string
- Python | Sort each String in String list
- Python | Check if a given string is binary string or not
- Python String | min()
- Python String
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

