-7

e.g.

a = 'abc123def'
b = 'abcdef'

I want a function which can judge whether b in a.

contains(a,b)=True

p.s. gap is also allowed in the represention of b, e.g.

b='abc_def'

but regular expressions are not allowed.

Quail Wwk
  • 25
  • 4
  • something like ```if b in a:```? – ewokx Aug 05 '20 at 04:29
  • 1
    Does this answer your question? [Does Python have a string 'contains' substring method?](https://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-substring-method) – ksbg Aug 05 '20 at 04:29
  • That's OK. But I prefer not to use 'if b1 in a and b2 in a'. – Quail Wwk Aug 05 '20 at 04:32
  • @QuailWwk, is gap formed by a special character or digit as well? Also, can you please provide more examples? This is confusing. Can `a` also have gaps? Does your current example represents the question well? – Namandeep_Kaur Aug 05 '20 at 04:44
  • 1
    It sounds like you are trying to check if the [longest common subsequence](https://en.wikipedia.org/wiki/Longest_common_subsequence_problem) of `a` and `b` is equal of the length of `b` (which is actually a lot simpler than finding the lcss). – ikegami Aug 05 '20 at 04:45
  • @Namandeep_Kaur a have no gap. The gap have no specific pattern,. It can be digits, characters and punctuations. – Quail Wwk Aug 05 '20 at 04:50

3 Answers3

2

If what you want to do is to check whether b is a subsequence of a, you can write:

def contains(a, b):
    n, m = len(a), len(b)
    j = 0
    for i in range(n):
        if j < m and a[i] == b[j]:
            j += 1
    return j == m
fanfly
  • 406
  • 2
  • 5
-1

Try using list comprehension:

def contains(main_string, sub_string):
    return all([i in main_string for i in sub_string])

NOTE: 'all' is a builtin function which takes an iterable of booleans and returns try if all are True.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
ViggyPiggy
  • 127
  • 5
-1
def new_contained(a,b):
   boo = False
   c = [c for c in a]
   d =  [i for i in b]
   if len(c)<=len(d):
     for i in c:
        if i in d:
          boo = True
   return boo  
S.R Keshav
  • 1,965
  • 1
  • 11
  • 14