-1

The issue I have is that I'm not able to get the correct part of my txt string. The txt string also has to be in the current order, I can't switch role and name.

   txt = \
    '''
    Company name
    leader: Claire
    cashier: Ole
    '''

    def role(name):
        start= txt.find(name)-len(name)
        end= txt.find('\n', start)
        return txt[start:end]

If I type role("Ole") I expect the output to be 'cashier'. The output I am getting though is 'r: Ole'.

  • What do you expect `txt.find(name)-len(name)` to do? it will always be negative which will mess the indexing when you use `start` – DeepSpace Oct 07 '19 at 19:12
  • @DeepSpace sorry, I find it a bit confusing. my intention for txt.find(name)-len(name) was that it would take the length of the name you enter in the function and start from right before the colon? – Daniel E Oct 07 '19 at 19:15
  • Negative indexing does not work this way. See https://stackoverflow.com/questions/509211/understanding-slice-notation – DeepSpace Oct 07 '19 at 19:17

2 Answers2

0
stringy = "cashier: Ole"
stringy.partition(':')[0]

you can use .partition and bring only the first element

this will work but if there is anything diff about your string it may break down.

stringy = """    Company name
    leader: Claire
    cashier: Ole"""
def role(name):
    slice = stringy.partition(name)[0]
    role_str = slice.split(' ')[-2]
    return role_str
Jeff R
  • 90
  • 8
0

You can create a dictionary that associates the names to the correspondent roles, so that it becomes very easy to retrieve them even in a much longer list:

txt = \
'''
Company name
leader: Claire
cashier: Ole
'''

t = txt.split()
roles = {t[i] : t[i-1].strip(':') for i in range(3, len(t), 2)}

def role(name):
    return roles[name]

Once set up, it's pretty intuitive.

Michele Bastione
  • 363
  • 3
  • 13