Home > Enterprise >  How to modify a specific substring in a list of strings in Python?
How to modify a specific substring in a list of strings in Python?

Time:06-13

Let's say I have a list like this:

rows = ['123', '456', '789']

and I try to modify the first character of the first string like this:

rows[0][0].replace('1','DDDD')

then when I print out the list, there is no change to it?

I know of a way to do it with list comprehension, but that iterates through the entire list which seems inefficient. Is there a way to just target one string in the list?

CodePudding user response:

.replace returns the mutated string, not changes it in place. You instead want to set your character to the returned value, like so:

rows[0]=rows[0].replace('1','DDDD')#changes all occurrences

If you only wanted to change the first character, you could do

rows[0]='DDDD' rows[0][1:]

But keep in mind that doesn't check the character.

CodePudding user response:

The function on it's own won't change the list value, you need to do this:

rows[0][0] = rows[0][0].replace('1','DDDD')

CodePudding user response:

rows = ['123', '456', '789']

1.using list comprehension, map function and lambda 2.Replace substring in list of strings

result = list(map(lambda st: str.replace(st, "3", "0"), rows)) result -> ['120', '456', '789']

  • Related