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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output :

The string after construction : abcdefghijklmno


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.