如何使用自定义函数结合split方法从全局字符串变量中返回指定人物的对应职位
解决方法
Let's get this function working properly! The issue with your current code is that splitting the entire string on : just chops up every part of the text at colons, which isn't what we need. Instead, we need to process each line individually to match names to their roles.
Here's the revised function that does exactly what you want—no modifications to the original strvariable required:
strvariable = '''\ Fictional Association leader: Marisa cashier: John IT-consultant: Jenny parking-manager: Marisa programmer: Jenny gardening-consultant: Marisa fire-chief: Marisa ''' def credentials(person): # Split the string into lines, remove empty lines and trim whitespace from each line formatted_lines = [line.strip() for line in strvariable.split('\n') if line.strip()] # Initialize an empty list to store matching positions matching_roles = [] # Skip the first line (it's the association name) and process each entry line for line in formatted_lines[1:]: # Split each line into role and name, trimming whitespace from both role, name = line.split(':') if name.strip() == person: matching_roles.append(role.strip()) return matching_roles
How it works:
- First, we split the global string into individual lines with
strvariable.split('\n'), then clean up each line by stripping whitespace and filtering out any empty lines (in case there are trailing newlines). - We skip the first line since it's just the association title, not a role-person entry.
- For each remaining line, we split on
:to separate the role and the person's name. We usestrip()to get rid of any extra spaces around the role and name. - If the cleaned-up name matches the
personparameter we passed in, we add the cleaned-up role to our result list. - Finally, we return the list of matching roles.
Testing this gives exactly the output you want:
>>> credentials('Marisa') ['leader', 'parking-manager', 'gardening-consultant', 'fire-chief']
内容的提问来源于stack exchange,提问作者throwaway123
相关产品推荐
相关产品推荐

