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:
- split by newline '\n'
- make a list comprehension to store the results
- filter lines only containing ':'
- split each item in the comprehension by ':'
- store only the first element of the split
- 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'))