Home > Software design >  Python: Pick String items
Python: Pick String items

Time:11-17

Has to be done in python 2.7, because of the assignment program.

Write a function def get_strings(mixed_list):, which returns a new list with all the string type items in the mixedList given as an argument. The order of the string items must match the original list. For example, if called with a list like this...

[1, 'a', 2, 'b', True, 'e']

The function should return a list like this:

['a', 'b', 'e']
l = []
s = string.ascii_letters
for i in range(random.randint(15,25)):
   r = random.randint(0,2)
   if r == 0:
     ind = random.randint(0, len(s) -1 )
     l.append(s[ind : ind   random.randint(1, 4) ])
   elif r == 1:
      l.append(random.randint(-50,50))
   else:
      l.append(random.choice([True, False, 1.0 / random.randint(1, 10) ]))

print ("Whole list:", l)
print ("Strings only:" , get_strings(l))

import random

CodePudding user response:

You can try this:

def get_strings(mixed_list):
    return [i for i in mixed_list if isinstance(i, str)]

For Python 2.7 as @Bernana suggested:

def get_strings(mixed_list):
    return [i for i in mixed_list if isinstance(i, basestring)]

CodePudding user response:

in python2.7 isinstance would not work with str but with basestring.

it should look like:

    lst = [1, 'a', 2, 'b', True, 'e']
    l = []
    print([x for x in lst if isinstance(x, basestring)])

CodePudding user response:

Consider utilizing a list comprehension along with isinstance:

def get_strings(mixed_list):
    return [x for x in mixed_list if isinstance(x, str)]

l = [1, 'a', 2, 'b', True, 'e']
print ("Whole list:", l)
print ("Strings only:" , get_strings(l))

Output:

Whole list: [1, 'a', 2, 'b', True, 'e']
Strings only: ['a', 'b', 'e']
  • Related