Change language

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 

Python | Get positional characters from a string Python functions: Questions

Python | Get positional characters from a string String Variables: Questions

Shop

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Best laptop for Zoom

$499

Best laptop for Minecraft

$590

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News

Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method