Home > Back-end >  write a function that take the first and last character of each string
write a function that take the first and last character of each string

Time:03-19

Question: write a function that take a list of strings as input and outputs a new list containing the first and last character of each string. example: firstlast(['TIM','EW','Sarah']) returns ['TM','ED','Sh']

My code is:

names = ["Kevin", "Wenyan", "Ed", "U"]

# create a function called 'firstlast' here

def firstlast(names):
    list=[]
    for name in names:
        for i in range(len(name)):
            if i == 0:
                list = name[i]
            if i == len(name) - 1:
                list =name[i]
                  
    return list
    
#print firstlast(names)
firstlast(names)

It returns this ['K', 'n', 'W', 'n', 'E', 'd', 'U', 'U'], not what the question wants.

CodePudding user response:

Try string slicing like a[1] Indexes : 0|1|2|3|4|5|6…etc The strong first starts on 0

CodePudding user response:

You don't need to use a loop within the loop because you already know which elements of name you want to access: the first one (0) and last one (-1). -1 accesses the last item/character. You can then directly concatenate them and append the resulting string to the list.

names = ["Kevin", "Wenyan", "Ed", "U"]

# create a function called 'firstlast' here

def firstlast(names):
    list=[]
    for name in names:
        list.append(name[0]   name[-1])

    return list
    
#print firstlast(names)
firstlast(names)

In case of "U" this will return "UU", not sure if that is what you want. Also it would return an Error if you hand an empty string to it. So you might want to catch these two cases by using an if-statement.

Also as a general rule it is better to avoid using the name of python builtins such as list as variable names, because that can cause problems in some cases.

  • Related