Ryan Asher Ryan Asher - 3 months ago 9
Python Question

Removing characters from indices within multiple lists

Just a really quick question I cannot figure out for the life of me, although it seems simple...

How do I delete the last 2 characters of each 4th index of a list, in a list? So in less confusing terms:

f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = []

L.append(f)
L.append(p)


So now L is:

L = [['yes', 'no', 'tot', 'foop\n'], ['ick', 'throw', 'tamp', 'lap\n']]


How would I go about getting writing a loop that would get rid of the \n at the end of every 4th index, within both lists (that could also be extended for more than just the 2 lists I have above in the list)?

I just want it to re-return L, without those \n's at the end of those last indices.

Answer
f = ['yes', 'no', 'tot', 'foop\n']
p = ['ick', 'throw', 'tamp', 'lap\n']

L = []

L.append(f)
L.append(p)

for i in range(len(L)):
    L[i][3] = L[i][3].rstrip('\n') # Use rstrip to strip the specified character(s) from the right side of the string.
print L

>>[['yes', 'no', 'tot', 'foop'], ['ick', 'throw', 'tamp', 'lap']]
Comments