Posts Tagged list

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)

, ,

No Comments

Python: removing repeated values in a list

CODE:
  1. list = ['one', 'two', 'three', 'one', 'one', 'four', 'two']
  2. #convert the list into a set.  An element can only exist once within a set
  3. set = set(list)
  4. #convert the set back into a list type
  5. list = list(set)
  6. print list

Are those variable names confusing? Let's look at that example again:

CODE:
  1. fruits = ['apple', 'bananas', 'cantaloupes', 'apple', 'apple', 'durian', 'bananas']
  2. #convert the list into a set.  An element can only exist once within a set
  3. fruits_unique = set(fruits)
  4. #convert the set back into a list type
  5. fruits = list(fruits_unique)
  6. print fruits

, ,

No Comments