Home > Software design >  Python3: By using a user-defined function, how can I return ONLY specific elements of a string varia
Python3: By using a user-defined function, how can I return ONLY specific elements of a string varia

Time:10-30

I am trying to write a function that will return specific elements of a global string variable upon a given parameter. In this scenario, I want it to return the credentials of fictional people. The solution should NOT have to alter anything in the variable.

strvariable = '''\
Fictional Association
leader: Marisa
cashier: John
IT-consultant: Jenny
parking-manager: Marisa
programmer: Jenny
gardening-consultant: Marisa
fire-chief: Marisa
'''

def credentials(person):
    print(strvariable.split(':')) # this is clearly incorrect and returns the whole string without ':'

Instead, I want the outcome to look as follows:

>>> credentials('Marisa')
['leader', 'parking-manager', 'gardening-consultant', 'fire-chief']

CodePudding user response:

...have a look below:

  1. split by newline '\n'
  2. make a list comprehension to store the results
  3. filter lines only containing ':'
  4. split each item in the comprehension by ':'
  5. store only the first element of the split
  6. add additional filter to capture only the person you want
s = '''\
Fictional Association
leader: Marisa
cashier: John
IT-consultant: Jenny
parking-manager: Marisa
programmer: Jenny
gardening-consultant: Marisa
fire-chief: Marisa
'''

s.split('\n')
[x for x in s.split('\n')]
[x for x in s.split('\n') if ':' in x]
[x.split(':') for x in s.split('\n') if ':' in x]
[x.split(':')[0] for x in s.split('\n') if ':' in x]
[x.split(':')[0] for x in s.split('\n') if ':' in x if 'Marisa' in x]

# putting all that logic together

def get_cred_for_person(who):
   return [x.split(':')[0] for x in s.split('\n') if ':' in x if who in x]

print('Marisa is a:', get_cred_for_person('Marisa'))
  • Related