1

I have a list of time that looks like this:

["0531","0950", "1232", "2241" ..."]

I need to insert a ":" inside every object in the list, in such a way I have:

["05:31", "09:50", ...]

How can I do that?

Tino Mosso
  • 165
  • 5

2 Answers2

2
old_list = ["0531", "0950", "1232", "2241"]
new_list = [a[0:2] + ":" + a[2:4] for a in old_list]

Then print(new_list) will print out ['05:31', '09:50', '12:32', '22:41'].

How does it work?

It creates a list, where each element is the first two characters of each element in the original list a[0:2] concatenated with a : concatenated with the next two a[2:4].

Ollie
  • 1,641
  • 1
  • 13
  • 31
2

Use a comprehension:

>>> l = ["0531","0950", "1232", "2241"]
>>> [f"{s[:2]}:{s[2:]}" for s in l]
['05:31', '09:50', '12:32', '22:41']
Netwave
  • 40,134
  • 6
  • 50
  • 93