0

Simple example would be to get prefix from two strings

s1 = "abcd666678"
s2 = "abcd777778"

Is it possible to get common prefix abcd using list comprehension. I am trying as below however I am getting abcd78, all common characters, how to break after abcd

"".join([s1[i] for i in range(min(len(s1), len(s2))) if s1[i]==s2[i]])
DuDa
  • 3,718
  • 4
  • 16
  • 36
  • Does this answer your question? [Using break in a list comprehension](https://stackoverflow.com/questions/9572833/using-break-in-a-list-comprehension) – ApplePie Jan 17 '21 at 18:10

2 Answers2

1

Use itertools.takewhile and zip:

>>> from itertools import takewhile
>>> ''.join(x for x, _ in takewhile(lambda t: t[0] == t[1], zip(s1, s2)))
'abcd'
chepner
  • 497,756
  • 71
  • 530
  • 681
1

There is a builtin function which does what you want: os.path.commonprefix

>>> import os
>>> s1 = "abcd666678"
>>> s2 = "abcd777778"
>>> os.path.commonprefix([s1, s2])
'abcd'
Asocia
  • 5,935
  • 2
  • 21
  • 46