Home > Software engineering >  To find what two string have in common
To find what two string have in common

Time:09-21

I have two strings:

var_1 = 'ebro EBI 310 TE Temperature data logger'
var_2 = 'EBRO EBI 310 TE USB-LOGGER'

how is it optimal (without regex and long loops) to create a third variable in which there will be text that enters both the first and second variables, in particular in the example above it will be

var_3 = 'EBRO EBI 310 TE'

PS or, it is better to compare 4 or more variables in this way and find the part of the text that occurs in all variables, and in which it does not occur - discard..

CodePudding user response:

Here is an example of how to compare four or more vars as you have stated at the exact position and any position,

var_1 = 'ebro EBI 310 TE Temperature data logger'
var_2 = 'EBRO EBI 310 TE USB-LOGGER'
var_3 = 'EBRO EBI 310 TE USB-THINGY'
var_4 = 'EBRO EBI 310 TE USB-THUGY'
# create a function to return only the characters that are the same in x amount of string arguments at the same position
def compare(*args):
    # convert args to lower case
    args = [x.lower() for x in args]
    return ''.join([x[0] for x in zip(*args) if all(y== x[0] for y in x)]).upper()

compare_result = compare(var_1, var_2, var_3, var_4)
print(compare_result)

# create a function to return only the characters that are the same in x amount of string arguments at any position
def compare_any(*args):
    # convert args to lower case
    args = [x.lower() for x in args]
    return ''.join([x[0] for x in zip(*args) if any(y.lower() == x[0].lower() for y in x)]).upper()
compare_any_result = compare_any(var_1, var_2, var_3, var_4)
print(compare_any_result)

Output:

EBRO EBI 310 TE 
EBRO EBI 310 TE TEMPERATU

CodePudding user response:

It's not a very long loop...

new_string = []
for i, char in enumerate((var_1 if var_1 > var_2 else var_2)): 
  if var_1[i] == var_2[i]: new_string.append(char)
  else: break
new_string = ''.join(new_string)
  • Related