Home > Net >  Sort of an OR operation on two strings in python
Sort of an OR operation on two strings in python

Time:08-27

I have two strings:

StringA = "SushantSingh"
StringB = "SinghRajput"

Desired resultant string is:

result = "SushantSinghRajput"

How to get the result string using some operations in python from StringA and StringB? A good/clean way. Basically sort of an OR Operation.

My attempt for others to view:

import difflib
StringA = "SushantSingh"
StringB = "SinghRajput"
res = ""
res_S = ""
res = [li[2] for li in difflib.ndiff(StringA,StringB)]
for ele in res:
    res_S =ele
print(res_S)

Out: 'SushantSinghRajput'

but I seek even less lines answer. more short version is:

import difflib
StringA = "SushantSingh"
StringB = "SinghRajput"
res = ''.join([li[2] for li in difflib.ndiff(StringA,StringB)])
print(res)

any other better way without using difflib ?

CodePudding user response:

A simple way to do that would be using startsWith and iterating over one string:

StringA = "SushantSingh"
StringB = "SinghRajput"

merged = ""

for index in range(len(StringA)):
    if StringB.startswith(StringA[index:]):
        merged = StringA[:index]   StringB
        break
else:
    merged = StringA   StringB

print(merged) 

But it is obviously not a one liner, if this was your requirement ...

CodePudding user response:

@Sami Tahri answer is good but I think it is better if you start from the end of of StringA is more efficient.

StringA = "SushantSingh"
StringB = "SinghRajput"

merged = ""
for i in range(len(StringA)-1, -1, -1):
    if StringB.startswith(StringA[i:]):
        merged = StringA[:i] StringB
        break
else:
    merged = StringA StringB
print(merged)
  • Related