howtos » Python: Inserting characters into a string

Python: Inserting characters into a string

Disclaimer: I’m a Python newbie … if you know of a more efficient way let me know!

I needed to take a sequence of 4 digits (eg 1145) and modify it to look like clock-time (eg “11:45″). After a bit of online (what else?) research I decided to take the approach of converting the integer to a string and then to a list (of characters). I then insert the extra character (ie the “:”) into the list at the right position. Finally, join the list elements together to form a new string.


time_int = 1145
time_str = str(time_int)
time_list = list(time_str)
time_list.insert(2, ‘:’) #insert the ‘:’ character into the list before position 2
time_str = “”.join(time_list)

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <code> <em> <strong>