3

Is there an easy way in python of creating a list of substrings from a list of strings?

Example:

original list: ['abcd','efgh','ijkl','mnop']

list of substrings: ['bc','fg','jk','no']

I know this could be achieved with a simple loop but is there an easier way in python (Maybe a one-liner)?

1
  • there can be many substrings . you have shown only from index [1-2].. Do you have a specific case. Commented Jun 26, 2013 at 9:27

4 Answers 4

4

Use slicing and list comprehension:

>>> lis = ['abcd','efgh','ijkl','mnop']
>>> [ x[1:3] for x in lis]
['bc', 'fg', 'jk', 'no']

Slicing:

>>> s = 'abcd'
>>> s[1:3]      #return sub-string from 1 to 2th index (3 in not inclusive)
'bc'
Sign up to request clarification or add additional context in comments.

2 Comments

Dammit, just a bit quicker than me! :)
thanks, it works :) (For some reason I can't accept your answer till in 11minutes)
1

With a mix of slicing and list comprehensions you can do it like this

listy = ['abcd','efgh','ijkl','mnop']
[item[1:3] for item in listy]
>> ['bc', 'fg', 'jk', 'no']

Comments

1

You can use a one-liner list-comprehension.

Using slicing, and relative positions, you can then trim the first and last character in each item.

>>> l = ['abcd','efgh','ijkl','mnop']
>>> [x[1:-1] for x in l]
['bc', 'fg', 'jk', 'no']

If you are doing this many times, consider using a function:

def trim(string, trim_left=1, trim_right=1):
    return string[trim_left:-trim_right]

def trim_list(lst, trim_left=1, trim_right=1):
    return [trim(x, trim_left, trim_right) for x in lst] 

>>> trim_list(['abcd','efgh','ijkl','mnop'])
['bc', 'fg', 'jk', 'no']

Comments

0

If you want to do this in one line you could try this:

>>> map(lambda s: s[1:-1], ['abcd','efgh','ijkl','mnop'])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.