Python | Get positional characters from a string



Method # 1: Using a loop
This is a crude method in which this task can be accomplished. In this we loop over the list of indices and concatenate the corresponding index characters from the string.

# Python3 code to demonstrate how it works
# Get positional characters from a string
# using a loop

  
# initialization string

test_str = " gfgisbest "

  
# print the original line

print ( " The original string is: " + test_str)

 
# initializing the index list

indx_list = [ 1 , 3 , 4 , 5 , 7 ]

 
# Get positional characters from a string
# using a loop

res = ``

for ele in indx_list:

  res = res + test_str [ele]

 
# print result

print ( "Substring of selective characters:" + res)

Output:

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

Method # 2: Using a generator expression + enumerate()
A combination of the above functions can be used to accomplish this task … In this, we start a loop using a generator expression and retrieve the indices using enumerate ().

# Python3 code to demonstrate how it works
# Get positional characters from string
# using generator expression + enumerate ()

 
# initialization string

test_str = "gfgisbest"

  
# print the original line

print ( "The original string is:" + test_str)

  
# initializing the index list

indx_list = [ 1 , 3 , 4 , 5 , 7 ]

  
# Get positional characters from a string
# using generator expression + enumerate ()

res = `` .join ((char for idx, char in enumerate (test_str) if idx in indx_list))

 
# print result

print ( "Substring of selective characters:" + res)

Exit:

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