Python | Get positional characters from String

Sometimes, while working with Python strings, we can have a problem in which we need to create a substring by joining the particular index elements from a string. Let’s discuss certain ways in which this task can be performed.

Method #1 : Using loop
This is brute method in which this task can be performed. In this, we run a loop over the indices list and join the corresponding index characters from string.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get positional characters from String
# using loop
  
# initializing string 
test_str = "gfgisbest"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing index list 
indx_list = [1, 3, 4, 5, 7]
  
# Get positional characters from String
# using loop
res = ''
for ele in indx_list:
    res = res + test_str[ele]
  
# printing result
print("Substring of selective characters : " + res)

chevron_right


Output :

The original string is : gfgisbest
Substring of selective characters : fisbs

 

Method #2 : Using generator expression + enumerate()
The combination of above functionalities can be used to perform this task. In this, we run a loop using generator expression and indices extraction is done with help of enumerate().

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Get positional characters from String
# using generator expression + enumerate()
  
# initializing string 
test_str = "gfgisbest"
  
# printing original string 
print("The original string is : " + test_str)
  
# initializing index list 
indx_list = [1, 3, 4, 5, 7]
  
# Get positional characters from String
# using generator expression + enumerate()
res = ''.join((char for idx, char in enumerate(test_str) if idx in indx_list))
  
# printing result
print("Substring of selective characters : " + res)

chevron_right


Output :

The original string is : gfgisbest
Substring of selective characters : fisbs



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.