Take the 2-minute tour ×

I have a string, 'RTKLOANGMSTTTS' and a list of tuples, [(2,5),(8,9)], that returns a string containing the letters 2-5 and 8-9 both inclusive, that is 'TKLOGM'. I was thinking something like:

def f(string, lst):
    for element in lst:
        if element in string:
            print string

But it does not return anything?

share|improve this question
So, you want to slice the string with the tuples in the list? If thats what you need, it's pretty easy in python. –  Matt Dec 15 '11 at 8:27

4 Answers 4

up vote 4 down vote accepted

Try this:

def f(source, lst):
    return "".join(source[start - 1:end] for start, end in lst)

What this will do is iterate over the lst, extracting the tuple into start and end on every iteration. Then it will create a new string as a slice from the source string, from start - 1 to end (we use start - 1 because you showed that 1 means the first character, but python uses 0-indexing, so we must substract one). Finally we join all the strings using "".join().

If you use an older version of Python that doesn't support the generator syntax, use this instead:

def f(source, lst):
    return "".join([source[start - 1:end] for start, end in lst])

It works exactly the same, but instead of working with a generator it explicitly creates a list which gets joined.

share|improve this answer
that will not give the answer needed by OP, you will have KLOAMS, not TKLOGM.... –  Cédric Julien Dec 15 '11 at 8:30
@Cédric Julien: Woops, I thought the OP was sane and used 0-indexing. I'll fix this. –  orlp Dec 15 '11 at 8:33
It doesn't work. I get the error: TypeError: 'function' object is not iterable –  Linus Svendsson Dec 15 '11 at 8:54
@LinusSvendsson: How are you using the function? It should be used like this: result = f("RTKLOANGMSTTTS", [(2,5),(8,9)]). –  orlp Dec 15 '11 at 8:55
Sorry, it is working now, thx.. –  Linus Svendsson Dec 15 '11 at 9:00
>>> l = [(2,5),(8,9)]
>>> ''.join(x[s-1:e] for (s,e) in l)
share|improve this answer

I think this is what you asking for. I can't test right now, but try:

def f(string, lst):
    getStr = ''
    for t in lst:
        begin, end = t
        getStr += string[begin-1:end]
    return getStr
share|improve this answer
def f(string, lst):
   for start, end in lst:
       s = string[start-1:end]
       if s:
           yield s

for s in f('RTKLOANGMSTTTS', [(2,5),(8,9)]):
    print s
share|improve this answer

Your Answer


