-2

I need help to replace a content in a list, but at a certain interval.

Lets say I have a list with this data:

a = ["word word word" , "word data word"]

And I want to replace word that is in character [9:13] for data so the output of the list would be this:

b = ["word word data" , "word data data"]

How could I do it in python? I've only found solutions that would replace everything that is named as word like the command replace.

Edit: I guess i tried to post a lighter version of my problem, I need to replace an invalid data for a valid data, but when I do it i can't risk replacing similar data that belongs there.

Replacing word for data in character [9:13]

a = ["word word word" , "word data othr" , "word, data word"]

Output should be:

b = ["word word data" , "word data othr" , "word, data data"]

Georgy
  • 12,464
  • 7
  • 65
  • 73
mixelsan
  • 5
  • 4

2 Answers2

0

Here is how you can use a list comprehension, slices and formatted strings:

a = ["word word word" , "word data word"]

b = [f'{s[:9]} data {s[14:]}' for s in a]

print(b)

Output:

['word word data', 'word data data']
Red
  • 26,798
  • 7
  • 36
  • 58
0

Try this:

for i,v in enumerate(a): 
    a[i] = v[:10] + 'data' + v[14:] 

then a will be:

['word word data', 'word data data']
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59