ajbentley ajbentley - 11 months ago 54
Python Question

How do I edit a string within a list of lists?

I have a list of lists each with 11 strings.

The last string is an 8-digit code where I need to retain the first three digits but delete the last five.

I'm pretty sure this can be done using indexing and slicing.

Example uses lists with 5 entries instead of 11.

Example =

[['a','b','c','d','2020BG1C'],['e','f','g','h','1997AF33'],['i','j','k','l', '1566IL2L']]

Desired_Outcome =

[['a','b','c','d','202'],['e','f','g','h','199'],['i','j','k','l', '156']]

Answer Source

You can't edit a string; they are immutable.

But you can slice off the unwanted parts (which creates a new string) from the last item of each sublist:

lst = [['a','b','c','d','2020BG1C'],['e','f','g','h','1997AF33'],['i','j','k','l', '1566IL2L']]
for sublist in lst:
     sublist[-1] = sublist[-1][:4]

# [['a', 'b', 'c', 'd', '2020'], ['e', 'f', 'g', 'h', '1997'], ['i', 'j', 'k', 'l', '1566']]

Some reference:

  1. Explain Python's slice notation
  2. Aren't Python strings immutable?