Hi all. I am having trouble with one of midterm practice problem questions again. I need to be able to get the First, Middle, and Last Name using the count function. However, my professor wants us to be using a name with more than one middle name, and I am having trouble making it print the first name on one line, the full middle name separately on another line, and the last name on another line. Any Help will be greatly appreciated.

Here's my code:

def getFirstName(fullname):
space = fullname.find(' ')
return fullname[0:space]

def getMiddleName(fullname):
count = fullname.count(' ')
temp = fullname
for i in range(count):
space = temp.find(' ')
temp = temp[space-1:]
return temp


def getLastName(fullname):
count = fullname.count(' ')
temp = fullname
for i in range(count):
space = temp.find(' ')
temp = temp[space+1:]
return temp


name = 'Benjamin de OMG I HAVE A LOT OF MIDDLE NAMES la Franklin'

fname = getFirstName(name)
mname = getMiddleName(name)
lname = getLastName(name)


print(fname)
print(mname)
print(lname)


This is what I keep getting for my result:
Benjamin
n de OMG I HAVE A LOT OF MIDDLE NAMES la Franklin
Franklin
>>>

Basically I need it to say:
Benjamin
de OMG I HAVE A LOT OF MIDDLE NAMES la
Franklin

Basically this code needs to print any names between the firstname and the lastname.

Dani AI

Generated

A few practical notes that address what went wrong and a clean, robust way to get first / middle(s) / last.

The original off-by-one in 's getMiddleName came from slicing at the wrong index while walking spaces, which inserted the last character of the first name into the middle string. was right that only the first and last delimiter matter for extraction, and correctly warned about extra user spaces making index-based logic fragile.

A simple, reliable approach is: strip leading/trailing whitespace, split on whitespace (this collapses multiple spaces), then take the first token, the last token, and join everything between as the middle. This handles any number of middle names and ignores repeated spaces.

name = name.strip()
parts = name.split()                 # splits on any whitespace
first = parts[0]                     # exists if len(parts) >= 1
middle = ' '.join(parts[1:-1])       # empty string if no middle names
last = parts[-1]                     # same as first if only one token

If the exercise strictly requires using space counting, apply strip() first, then use count(' ') to decide how many spaces to step through and find the nth space positions; prefer rfind or tracking indices rather than searching for the last name string (searching by substring can match earlier occurrences of the same token).

Corner cases to consider: single-token names, two-token names (no middle), leading/trailing/multiple spaces (strip + split handles those), hyphenated or multiword family names and common suffixes (Jr., III) or particles (de, van, la) — real-world name parsing can be much more involved, so for a midterm solution document the assumed input rules and handle length checks to avoid IndexError.

Recommended Answers

All 9 Replies

Anyone?

You really only need to use the first and last space, but count can be used to find how many spaces to index.

fullname = "one two three four five"
ct = fullname.count(' ')
idx=0
idx_list=[]
for ctr in range(ct):
    idx=fullname.find(" ", idx)
    idx_list.append(idx)
    idx += 1
print idx_list

first=fullname[:idx_list[0]]
print first
middle=fullname[idx_list[0]+1:idx_list[-1]]
print middle
last=fullname[idx_list[-1]+1:]
print last

#easier
idx_first=fullname.find(" ")
idx_last=fullname.rfind(" ")
print "\n", idx_first, idx_last
first=fullname[:idx_first]
print first
middle=fullname[idx_first+1:idx_last]
print middle
last=fullname[idx_last+1:]
print last

For me it is ununderstandable why on earth you would count spaces.

For me it is ununderstandable why on earth you would count spaces.

Ask my teacher not me :\

You really only need to use the first and last space, but count can be used to find how many spaces to index.

fullname = "one two three four five"
ct = fullname.count(' ')
idx=0
idx_list=[]
for ctr in range(ct):
    idx=fullname.find(" ", idx)
    idx_list.append(idx)
    idx += 1
print idx_list

first=fullname[:idx_list[0]]
print first
middle=fullname[idx_list[0]+1:idx_list[-1]]
print middle
last=fullname[idx_list[-1]+1:]
print last

#easier
idx_first=fullname.find(" ")
idx_last=fullname.rfind(" ")
print "\n", idx_first, idx_last
first=fullname[:idx_first]
print first
middle=fullname[idx_first+1:idx_last]
print middle
last=fullname[idx_last+1:]
print last

as long as you have not:

fullname = " one  two  three  four five  "

as long as you have not:

fullname = " one  two  three  four five  "

I fixed the Middle part of my code with this:


def getMiddleName(fullname):
space=fullname.find(' ')
end = fullname.find(getLastName(fullname))
return fullname[space+1:end]

What is different from MY code than yours?

Ending Code =

def getFirstName(fullname):
space = fullname.find(' ')
return fullname[0:space]

def getMiddleName(fullname):
space=fullname.find(' ')
end = fullname.find(getLastName(fullname))
return fullname[space+1:end]

def getLastName(fullname):
count = fullname.count(' ')
temp = fullname
for i in range(count):
space = temp.find(' ')
temp = temp[space+1:]
return temp


name = 'Benjamin de la OMG I have a lot of middle names Franklin'

fname = getFirstName(name)
mname = getMiddleName(name)
lname = getLastName(name)


print(fname)
print(mname)
print(lname)

Results:
Benjamin
de la OMG I have a lot of middle names
Franklin
>>>

You are finding the last name to get to the end of middle name. I am finding the last space.

And still the input should be stripped from extra spaces which easily come to user input. Then it would be not much more to just split the name and rejoin the middle names with only one space. Otherwise really robbust function should first read spaces before name and ignore them and at end of names it should still check that last space is not after every letter. This comes all too complicated. Of course this is only hypothetical excersise, but I prefer more practical ones, practicing to write really robust code using all available means, not artificial 'do this without best tools to do it' excesises.

Thanks for all the help everyone :).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.