You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用自定义函数结合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 use strip() to get rid of any extra spaces around the role and name.
  • If the cleaned-up name matches the person parameter 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 23:22:27