I have a list named player_home_run
, and the way that my program works is that sometimes, empty string is entered to it, and sometimes, words and other strings are entered into it. After a loop, the string sometimes looks like this:
['', '', '', '', 'Perez', '', '', '', 'Guerrero']
I would like to make a small loop that would delete all the empty spaces and leave me with only the names in the string. The length of the string should be the same as the # of names.
Should look like this:
['Perez', 'Guerrero']
I want to avoid using filter.
Edit: I figured out the ans right after posting this question.
Here's the code
if hit == True:
print(player_home_run, '# of homeruns')
run_calc = True
while run_calc == True:
if '' in player_home_run:
player_home_run.remove('')
ttl_runs = player_home_run
else:
print('no more whitespace.')
print(ttl_runs, ' ttl runs')
run_calc = False
CodePudding user response:
You could do a comprehension, like:
player_home_run = [item for item in player_home_run if item != ""]
CodePudding user response:
If you want to do a loop, then simply qualifying each iteration with an if statement will suffice. Here is an example:
listA = ['', '', '', '', 'Perez', '', '', '', 'Guerrero']
listB = []
for item in listA:
if item != "":
listB.append(item)
listA = listB
print listA
Here is the output for this script:
['Perez', 'Guerrero']