Home > Software engineering >  Changing the elements in a string that follow a particular pattern
Changing the elements in a string that follow a particular pattern

Time:12-14

So I have a list containing years. However, there are typing errors in the list. kindly check the following list.

list=[999.0,1006.0,1007.0,1008.0,1009.0,1010.0,1015.0,2006,2007,2008,2010,2015,2009]

So I want to replace the first two digits '10' with '20'.

CodePudding user response:

Use if, else in list squares

If elements in the list are strings

lst  = ['999.0','1006.0','1007.0','1008.0','1009.0','1010.0','1015.0','2006','2007','2008','2010','2015','2009']
    
  [x.replace('10','20') if x.startswith('10') else x for x in lst ]

If elements in the list are not strings

[str(int(x)).replace('10','20') if str(int(x)).startswith('10') else str(int(x)) for x in lst2 ]

CodePudding user response:

Using the Python re library you could convert the years in the list to strings and use a re.sub and then convert them back to ints like this (the inner int() is to remove the decimals):

import re
for i in range(len(list)):
    list[i] = int(re.sub("10([0-9]{2})", r"20\1", str(int(list[i]))))

list in:

[999.0,1006.0,1007.0,1008.0,1009.0,1010.0,1015.0,2006,2007,2008,2010,2015,2009]

list out:

[999, 2006, 2007, 2008, 2009, 2010, 2015, 2006, 2007, 2008, 2010, 2015, 2009]

If you want to convert years like 999 to 1999 as well, you could use a simple comparison as well:

import re
for i in range(len(list)):
    list[i] = int(re.sub("10([0-9]{2})", r"20\1", str(int(list[i]))))
    if list[i] < 1000: list[i]  = 1000

list out:

[1999, 2006, 2007, 2008, 2009, 2010, 2015, 2006, 2007, 2008, 2010, 2015, 2009]
  • Related