views:

110

answers:

5

How do I remove a character from an element in a list?

Example:

mylist = ['12:01', '12:02']

I want to remove the colon from the time stamps in a file, so I can more easily convert them to a 24hour time. Right now I am trying to loop over the elements in the list and search for the one's containing a colon and doing a substitute.

for num in mylist:
    re.sub(':', '', num)

But that doesn't seem to work.

Help!

+4  A: 
for i, num in enumerate(mylist):
    mylist[i] = num.replace(':','')
TooAngel
By default, I would go for this solution because you re-nest the new strings into the same list object. List comprehension approach detaches the result from original list pointer. When the list is property of a complex object, and you want that complex object to have the updated list, you will have to assign the new list back to a property, which is very un-pythonic.
ddotsenko
+12  A: 

Use a list comprehension to generate a new list:

>>> mylist = ['12:01', '12:02']
>>> mylist = [s.replace(':', '') for s in mylist]
>>> print mylist
['1201', '1202']

The reason that your solution doesn't work is that re.sub returns a new string -- strings are immutable in Python, so re.sub can't modify your existing strings.

Pär Wieslander
List comprehension to the rescue!
jathanism
Is there any advantage of list comprehensions to standard for loops, or just readability or length of the code?
TooAngel
@TooAngel: It is more awesome ;)
Felix Kling
@TooAngel: In addition to readability and reduced code length, list comprehensions also execute faster.
Daniel Stutzbach
@Daniel Stutzbach: Not always. It depends on what you are doing in the list comprehension (e.g. if you are using nested list comprehension). Sometimes you can gain a lot more performance using ordinary `for` loops.
Felix Kling
Thanks ya'll! I am totally new to python (obviously =) and I had no idea about list comprehensions. I have been looking for something like this. You just saved me so much time!
lollygagger
@Felix Kling: Obviously a better algorithm will be faster. I was referring only to cases where the list comprehension and the for loop are identical except for the syntax.
Daniel Stutzbach
A: 

You have to insert the return of re.sub back in the list. Below is for a new list. But you can do that for mylist as well.

mylist = ['12:01', '12:02']
tolist = []
for num in mylist:
  a = re.sub(':', '', num)
  tolist.append(a)

print tolist
sambha
+7  A: 

The list comprehension solution is the most Pythonic one, but, there's an important twist:

mylist[:] = [s.replace(':', '') for s in mylist]

If you assign to mylist, the barename, as in the other answer, rather than to mylist[:], the "whole-list slice", as I recommend, you're really doing something very different than "replacing entries in the list": you're making a new list and just rebinding the barename that you were previously using to refer to the old list.

If that old list is being referred to by multiple names (including entries in containers), this rebinding doesn't affect any of those: for example, if you have a function which takes mylist as an argument, the barename assignment has any effect only locally to the function, and doesn't alter what the caller sees as the list's contents.

Assigning to the whole-list slice, mylist[:] = ..., alters the list object rather than mucking around with switching barenames' bindings -- now that list is truly altered and, no matter how it's referred to, the new value is what's seen. For example, if you have a function which takes mylist as an argument, the whole-list slice assignment alters what the caller sees as the list's contents.

The key thing is knowing exactly what effect you're after -- most commonly you'll want to alter the list object, so, if one has to guess, whole-list slice assignment is usually the best guess to take;-). Performance-wise, it makes no difference either way (except that the barename assignment, if it keeps both old and new list objects around, will take up more memory for whatever lapse of time both objects are still around, of course).

Alex Martelli
A: 

Strings in python are immutable, meaning no function can change the contents of an existing string, only provide a new string. Here's why.

See here for a discussion on string types that can be changed. In practice though, it's better to adjust to the immutability of strings.

Ben Gartner