python - How do I loop through each string in my list? -
i tried piece of code, performs function on first string in list:
returns first , last 2 characters of given list of strings
def both_ends(list): finallist = [] s in list: if s > 2: return s[0] + s[1] + s[-2] + s[-1] else: return s finallist.append(s) return finallist list = ('apple', 'pizza', 'x', 'joke') print both_ends(string)
how make function run through of strings in list?
yes, because returning result directly , returns after go through first string itself. instead should put result in finallist
create , return result @ end.
and other things -
as said in other answer, want check length of string.
the length of string should greater 4 , otherwise, end adding characters multiple times.
do not use names
list
variables, ends shadowing builtin functions , not able uselist()
create list after that.last issue should call function list, not
string
.
example -
def both_ends(list): finallist = [] s in list: if len(s) > 4: finallist.append(s[:2] + s[-2:]) else: finallist.append(s) return finallist
an easier way -
def both_ends(s): return s[:2] + s[-2:] if len(s) > 4 else s lst = ('apple', 'pizza', 'x', 'joke') print map(both_ends, lst) #you need `list(map(...))` python 3.x
demo -
>>> def both_ends(s): ... return s[:2] + s[-2:] if len(s) > 4 else s ... >>> lst = ('apple', 'pizza', 'x', 'joke') >>> print map(both_ends, lst) ['aple', 'piza', 'x', 'joke']
or list comprehension , though me makes bit less readable -
[s[:2] + s[-2:] if len(s) > 4 else s s in lst]
demo -
>>> lst = ('apple', 'pizza', 'x', 'joke') >>> [s[:2] + s[-2:] if len(s) > 4 else s s in lst] ['aple', 'piza', 'x', 'joke']
Comments
Post a Comment