ala
ala

Reputation: 224

Create new list of substrings from list of strings

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)?

Upvotes: 3

Views: 3116

Answers (4)

Shaddy
Shaddy

Reputation: 163

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

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

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43507

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']

Upvotes: 1

Henrik Andersson
Henrik Andersson

Reputation: 47222

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']

Upvotes: 1

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

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'

Upvotes: 4

Related Questions