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

Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
ala
  • 224
  • 3
  • 16

4 Answers4

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'
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
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']
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92
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']
Community
  • 1
  • 1
Inbar Rose
  • 41,843
  • 24
  • 85
  • 131
0

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

>>> map(lambda s: s[1:-1], ['abcd','efgh','ijkl','mnop'])
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
Shaddy
  • 153
  • 1
  • 8