Home > Blockchain >  How to add a colon in a string, Python?
How to add a colon in a string, Python?

Time:01-22

I've got an array of elements of 4 numbers that are classed as strings, and I want to add a colon in between 2 of the numbers of every element so it looks like a time, but how do you do this:

STarray = ['0712', '0819', '1131', '1352', '1401']

CodePudding user response:

You can use list comprehensions for this.

Something like

STarray = [f"{el[:2]}:{el[2:]}" for el in STarray]

CodePudding user response:

Tou could use old style formatting in a list comprehension:

['%s%s:%s%s'%(*s,) for s in STarray]

# ['07:12', '08:19', '11:31', '13:52', '14:01']

CodePudding user response:

Here is another way using .format():

new = ["{}{}:{}{}".format(*item) for item in STarray]
  •  Tags:  
  • Related