Home > Software engineering >  Confused about the type of parameter that goes into this method
Confused about the type of parameter that goes into this method

Time:09-22

I'm trying to understand how this code works, we have:

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
          'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):

    return person.split()[0]   ' '   person.split()[-1]

So we are given a list, and this method is supposed to basically delete everything in the middle between "Dr." and the last name. As far as I know, the split() function cannot be used for lists, but for strings. so person must be a string. However, we also add [0] and [-1] to person, which means we should be getting the first and last character of "person" but instead, we get first word and last word. I cannot make sense of this code! May you please help me understand?

Any help is greatly appreciated, thank you :)

CodePudding user response:

The split function splits the string into a list of words. And then we select the first and last words to form the output.

>>> person = 'Dr. Christopher Brooks' 
>>> person.split()
['Dr.', 'Christopher', 'Brooks']
>>> person.split()[0]
'Dr.'
>>> person.split()[-1] 
'Brooks'

CodePudding user response:

This is not a real answer, just adding this for clarification on how the function would be used, given a list of strings.

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson',
          'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']


def split_title_and_name(person: str):

    return person.split()[0]   ' '   person.split()[-1]


# This code does not actually run (I guess this might have been what you were trying)
# result = split_title_and_name(people)

# Using a for loop to print the result of running function over each list element
print('== With loop')
for person in people:
    result = split_title_and_name(person)
    print(result)

# Using a list comprehension to get the same results as above
print('== With list comprehension')
results = [split_title_and_name(person) for person in people]
print(results)

CodePudding user response:

Python's split() method splits a string into a list. You can specify the separator, the default separator is any whitespace. So in your case, you didn't specify any separator and therefore this function will split the string person into ['Dr.', 'Christopher', 'Brooks'] and therefore [0] = 'Dr.' and [-1] = 'Brooks'.

The syntax for split() function is: string.split(separator, maxsplit), here both parameters are optional.

If you don't give any parameters, the default values for separator is any whitespace such as space, \t , \n , etc and maxsplit is -1 (meaning, all occurrences)

You can learn more about split() on https://www.w3schools.com/python/ref_string_split.asp

  • Related