-2

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'

WincyGaming
  • 29
  • 1
  • 2
  • 7
  • Possible duplicate of [Split string into a list in Python](http://stackoverflow.com/questions/743806/split-string-into-a-list-in-python) – aluriak Nov 18 '16 at 11:31
  • @aluriak I don't think this is duplicate of that one you linked. This is more than just splitting. – Lafexlos Nov 18 '16 at 11:32
  • You can try writing a function to achieve this. But I don't think you can achieve this using index. – arulmr Nov 18 '16 at 11:32

4 Answers4

0

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'
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126
0

This shuld work:

string = 'this_is_my_string'

words = string.split('_')
idx = 0
indexes = {}
for word in words:
    for i in range(len(word)):
        idx += 1
        indexes[idx] = word

print(indexes[1]) # this
print(indexes[12]) #string
0

The following code works. You can change the index and string variables and adapt to new strings. You can also define a new function with the code to generalize it.

string = 'this_is_my_string'

sp = string.split('_')
index = 12
total_len = 0
for word in sp:
    total_len += (len(word) + 1)    #The '+1' accounts for the underscore
    if index < total_len:
        result = word
        break
print result
Jalo
  • 1,131
  • 1
  • 12
  • 28
0

A little bit of regular expression magic does the job:

import re

def wordAtIndex(text, pos):
    p = re.compile(r'(_|$)')
    beg = 0
    for m in p.finditer(text):
        #(end, sym) = (m.start(), m.group())
        #print (end, sym)
        end = m.start()
        if pos < end: # 'pos' is within current split piece
           break
        beg = end+1   # advance to next split piece
    if pos == beg-1:  # handle case where 'pos' is index of split character
        return ""
    else:
        return text[beg:end]

text = 'this_is_my_string'
for i in range(0, len(text)+1):
    print ("Text["+str(i)+"]: ", wordAtIndex(text, i))

It splits the input string at '_' characters or at end-of-string, and then iteratively compares the given position index with the actual split position.

TomR8
  • 102
  • 4