Home > Software engineering >  how to insert unique string into a string builder even if it is a substring
how to insert unique string into a string builder even if it is a substring

Time:12-04

i have the below code, and the contents of self.asStringToCopyFromStatment is as shown below. the problem i have is, given a row with the following values 4.0 -99 13.07 -99 i it will not be inserted into the string self.asStringToCopyFromStatment because the in operator will assume, that it is already exists as it contains the value 44.0 -99 13.07 -99 i want the strings like:

4.0 -99 13.07   -99
-99 19.0    -99 13.9  
0   -99 14.8    -9

for example to be inserted into self.asStringToCopyFromStatment because they are unique. as long as a particular string is unique i want to add it to self.asStringToCopyFromStatment

code:

def appendDataRow(self):
    row = "{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))
    if (not row in self.asStringToCopyFromStatment()):
        self.inputStringToCopyFromStatement ="{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))
        

data/contents of self.inputStringToCopyFromStatement:

51.0    -99 14.26   -99
-99 29.0    -99 13.21
-99 19.0    -99 13.94 #<====================HERE
-99 27.0    -99 14.11
-99 7.0 -99 13.84
-99 3.0 -99 11.25
-99 10.0    -99 11.4
-99 15.0    -99 11.15
23.0    -99 11.43   -99
44.0    -99 13.07   -99 #<====================HERE
85.0    -99 14.66   -99
86.0    -99 14.78   -99
92.0    -99 14.8    -99 #<====================HERE
91.0    -99 14.76   -99

CodePudding user response:

You can use regex to check that row is indeed found at the beginning of a line:

import re

def appendDataRow(self):
    row = "{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))
    if not re.search(rf'^{row}', self.asStringToCopyFromStatment(), re.MULTILINE):
        self.inputStringToCopyFromStatement ="{0}\t{1}\t{2}\t{3}\n".format(str(self.getAoC1()),str(self.getAoC2()),str(self.getAvgH1()),str(self.getAvgH2()))

^ combined with the flag re.MULTILINE matches the beginning of a line.

  • Related