WincyGaming WincyGaming - 20 days ago 5
Python Question

Find out word at specific index

I have a string with multiple words separated by underscores like this:

string = 'this_is_my_string'


And let's for example take string[n] which will return a letter.

Now for this index I want to get the whole word between the underscores.

So for string[12] I'd want to get back the word 'string' and for string[1] I'd get back 'this'

Answer

Very simple approach using string slicing is to:

  • slice the list in two parts based on position
  • split() each part based on _.
  • concatenate last item from part 1 and first item from part 2

Sample code:

>>> my_string = 'this_is_my_sample_string'
#                              ^ index 14
>>> pos = 14

>>> my_string[:pos].split('_')[-1] + my_string[pos:].split('_')[0]
'sample'