Reputation: 22747
This is my Python code (I am using Python 2.7.6):
cn = ['here,', 'there']
>>> for c in cn:
if c.endswith(','):
c = c[:-1]
>>> print(cn)
['here,', 'there']
As you can see, cn[0]
still has the trailing comma even though I did c = c[:-1]
. How do I change cn[0]
so that it equals 'here'
without the trailing comma?
Upvotes: 0
Views: 417
Reputation: 2641
The problem is that you assign a new value to c
but do not update the list.
In order to manipulate the list in place you would need to do something like this:
cn = ['here,', 'there']
for index, c in enumerate(cn):
if c.endswith(','):
cn[index] = c[:-1]
print(cn)
['here', 'there']
Enumerate gives you all elements in the list, along with their index, and then, if the string has a trailing comma you just update the list element and the right index.
The problem with your code was that c
was simply holding the string 'here,'
. Then you created a new string whithou the comma and assigned it to c
, this did not affect the list cn
. In order to have any effect on the list you need to set the new value at the desired position.
You could also use list comprehension to achive the same result which might be more pythonic for such a small task: (as mentioned by @AdamSmith)
cn = [c[:-1] if c.endswith(',') else c for c in cn]
This does creates a new list from cn
where each element is returned unchanged if it does not end with ,
and otherwise the comma is cut off before returning the string.
Another thing you could use would be the built-in rstrip
function, but it would remove all trialing commas, not just one. It would look something like this (again @AdamSmith pointed this out):
cn = map(lambda x: x.rstrip(','), cn)
Upvotes: 5
Reputation:
You're changing the loop variable c
, but you aren't changing the list cn
. To change the list cn
, instead of looping through its values, loop through its indexes. Here's an implementation.
for c in range(len(cn)):
if cn[c].endswith(','):
cn[c] = cn[c][:-1]
Upvotes: 0
Reputation: 28983
What you did was copy the string with an edit, and store it in a new variable named c
, with a name that clashed with the original c
and overrode it.
Since you didn't change the original, it stays unchanged when the new one goes out of scope and gets cleared up.
You could do something like this to make a new list, containing the changed strings:
newlist = [c.strip(',') for c in cn]
Or, more closely to your example while keeping this approach:
cn = [c[:-1] if c.endswith(',') else c for c in cn]
The alternate loop-with-enumerate approach in another answer will work, but I'm avoiding it because in general, changing lists while iterating over them can lead to mistakes unless done carefully, and that makes me think it's a bad habit to get into in cases where there's another reasonably neat approach.
Upvotes: 1