0

I have following code below.

class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        splitName = name.split(' ')
        surname = splitName.pop()
        for i in range(len(splitName)):
            print('Name: %s' % splitName[i])

        return('Surname: %s' % surname)


np = NameParser()

print(np.getName("ali opcode goren"))

# output: name: ali, name: opcode, surname: goren

How do i return two values? Like following code:

for i in range(len(splitName)):
    return('Name: %s' % splitName[i])

return('Surname: %s' % surname)

# output: name ali: (error) i want all values name, name, surname

I want all values but just one output. How can I solve this problem?

10
  • 1
    What is your expected output? Commented Apr 23, 2015 at 18:12
  • Not expected. Output for two return: ali goren. Output for one print and one return: ali opcode goren (i want this) Commented Apr 23, 2015 at 18:14
  • return "Name: %s, Name: %s, Surname: %s"%(splitName[0], splitName[1], splitName[2]) and need to do exception handling when some name is missing in the input string. Commented Apr 23, 2015 at 18:20
  • or just return split list return splitName Commented Apr 23, 2015 at 18:26
  • @VivekSable thanks but this is manual. i want automatic. example: abc cb cde ffe ags dle like => split[0,1,2,3,4]. but your code not automatic. thanks for your help. Commented Apr 23, 2015 at 18:26

5 Answers 5

3
  1. Split: Split name by space and then do list comprehension again to remove the empty string from the list.
  2. POP: get last item from the list by pop() method and assign it to surname variable.
  3. Exception Handling: Do exception handling during pop process. If the input is empty then this will raise an IndexError exception.
  4. string concatenate: Iterate every Item from the list by for loop and assign the value to user_name variable.
  5. Concatenate surname in string again.
  6. Display result.

Demo:

class NameParser:
    def __init__(self):
        pass

    def getName(self, name):
        #- Spit name and again check for empty strings.
        splitName = [i.strip() for i in name.split(' ') if i.strip()]
        #- Get Surname. 
        try:
            surname = splitName.pop()
        except IndexError:
            print "Exception Name for processing in empty."
            return ""
        user_name = ""
        for i in splitName:
            user_name = "%s Name: %s,"%(user_name, i)
        user_name = user_name.strip()

        user_name = "%s Surname: %s"%(user_name, surname)
        return user_name


np = NameParser()
user_name = np.getName("ali      opcode       goren      abc")
print "user_name:", user_name

Output:

user_name: Name: ali, Name: opcode, Name: goren, Surname: abc
Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        listy = [] # where the needed output is put in
        splitName = name.split(' ')

        for i in range(len(splitName)):
            if i==(len(splitName)-1):#when the last word is reach
                listy.append('Surname: '+ splitName[i])
            else:
              listy.append('Name: '+ splitName[i])


        return listy


nr = NameParser()

print(nr.getName("ali opcode goren"))

# output: name: ali, name: opcode, surname: goren

whithout loop:

class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        listy = [] # where the needed output is put in
        splitName = name.split(" ")
        listy ="Name",splitName[0],"Name",splitName[1],"Surname",splitName[2]



        return listy


nr = NameParser()

print(nr.getName("ali opcode goren"))

# output: name: ali, name: opcode, surname: goren

9 Comments

I'm sorry. Not working. Just output: Name: ali I want like: Name: ali, Name: opcode, Surname: goren if i use print, it's work.
Thanks i get "goren" :). I can't get other values. I can solve, I guess.
I add also another code for when you don't want a loop. You ask it in another comment.
@MartijnvanWezel: in second code why you define listy = [] ? need this statement?
You always have to declare a list how big he will be. So to say he is empty in my code he will be declared. When you want to fill the list, use append this will add a something what you want to the list
|
1

Try to use yield

class NameParser:

    def __init__(self):
        self.getName

    def getName(self, name):
        splitName = name.split(' ')
        surname = splitName.pop()
        for i in range(len(splitName)):
            yield ('Name: %s' % splitName[i])

        yield ('Surname: %s' % surname)


np = NameParser()

for i in (np.getName("ali opcode goren")):
    print i

2 Comments

Thanks it's work! :) How to use this code without your for loop?
Read this question and its answers. Ali, to learn about yield.
1

you can just do this:

def getName(self, name):
    return name.split(' ')

It will return a tuple

def get_name(name):
   return name.split(' ')

>>> get_name("First Middle Last")
['First', 'Middle', 'Last']

Comments

0

or you can try

class test():
    map = {}
    for i in range(10):
        map[f'{i}'] = i
    return map

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.