To find what two string have in common

Viewed 66

I have two strings:

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

How can I (without regex and long loops) create a third variable that contains the matching characters from both the first and second variables? For example, the output would be;

var_3 = 'EBRO EBI 310 TE'

Can I compare four or more variables in the same way and find the part of the string that occurs in all variables and where it does not occur?

2 Answers

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

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