e9e9s
e9e9s

Reputation: 955

Length of string within a list of strings python

I'm iterating over a list that I'm trying to extract data from that looks like this:

for i in lst: 
    print(i.split('-'))


... output

['a', 'doa', 'a', 'h5t']
['a', 'rne']
['a', 'ece']
['a', 'ece']
['a', 'tnt', 'c', 'doa', 'd', 'nvc', 'a', 'nnm', 'a', 'h5t']
['a', 'tps']

My goal is to extract all the strings within each list that 3 characters long. If I do

len(i.split('-')) 

in which case the above would look like:

4
2
2
2
10
2

in the loop than I just get the length of each unique string in the list. My question is how can I get a count of the characters in each string in each list?

EDIT:

The output should look like:

['doa', 'h5t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']

Upvotes: 0

Views: 2000

Answers (3)

quamrana
quamrana

Reputation: 39354

This code:

lst = ['a-doa-a-h2t','a-rne','a-ece','a-ece','a-tnt-c-doa-d-nvc-a-nnm-a-h5t','a-tps']
for item in lst:
    words = item.split('-')
    print([word for word in words if len(word) == 3])

produces output something like your requirement:

['doa', 'h2t']
['rne']
['ece']
['ece']
['tnt', 'doa', 'nvc', 'nnm', 'h5t']
['tps']

Upvotes: 2

timgeb
timgeb

Reputation: 78650

My goal is to extract all the strings within each list that 3 characters long.

A nested list comprehensions will do the trick.

>>> l = ['a-bc-def-ghij-klm', 'abc-de' 'fg-hi']
>>> [[x for x in s.split('-') if len(x) == 3] for s in l]
[['def', 'klm'], ['abc']]

Upvotes: 3

Chrispresso
Chrispresso

Reputation: 4061

You need another loop to extract each word in the split like so:

for item in lst:
  for word in item.split('-'):
    if len(word) == 3:
      print(word)

Upvotes: -1

Related Questions