0

There is something wrong with my control flow but i can't figure it out. I am trying to get rid of all non-numeric characters. The output is supposed to look like:

fixed_times = ['0700', '1200', '2010', '1025', '1235', '1410']

But my program is only appending '1410' to fixed_times

This is my code:

event_times = ['07:00.', '12:00.', '20:10.', '10:25.', '12:35.', '14:10.']

count = 0 
j = 0
while count < len(event_times):
    fixed_times = []
    new_time = ""

    time = event_times[j]
    i = 0
    while i < len(time):
        if time[i].isdigit():
            new_time += str(time[i])
    
        i += 1
    fixed_times.append(new_time)
    j += 1
    count += 1

print(fixed_times)
b985
  • 13
  • 2
  • Does this answer your question? [How can I collect the results of a repeated calculation in a list, dictionary etc. (or make a copy of a list with each element modified)?](https://stackoverflow.com/questions/75666408/how-can-i-collect-the-results-of-a-repeated-calculation-in-a-list-dictionary-et) – mkrieger1 Apr 17 '23 at 10:28

2 Answers2

1

Your program is recreating the list fixed_times at each iteration, so the previous appended values are lost. You should move the variable declaration out of your first while loop like this:

# ...
fixed_times = []
while count < len(event_times):
   # ...
stellasia
  • 5,372
  • 4
  • 23
  • 43
0

You don't need to use while, simple list comprehension is enough:

event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]

out = ["".join(i for i in t if i.isdigit()) for t in event_times]
print(out)

Prints:

['0700', '1200', '2010', '1025', '1235', '1410']

Or:

import re

event_times = ["07:00.", "12:00.", "20:10.", "10:25.", "12:35.", "14:10."]

out = ["".join(re.findall(r"\d", t)) for t in event_times]
print(out)
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • Sorry, should've clarified that this is for a school assignment. I can't trivialise the problem by using list comprehension so i had to use a while loop – b985 Apr 11 '21 at 18:01
  • 1
    Completely unreadable functional approch for fun: `list(map(lambda event_time: "".join(filter(lambda char: char.isdigit(), event_time)), event_times))` – user8408080 Apr 11 '21 at 18:02