2

I wanted to ask if there is any way of finding a sequence of characters from a bigger string in python? For example when working with urls i want to find www.example.com from http://www.example.com/aaa/bbb/ccc. If found, it should return True.

Or is there any other way to do so? Thanks in advance!

hnvasa
  • 830
  • 4
  • 13
  • 26
  • 2
    possible duplicate of [Does Python have a string contains method?](http://stackoverflow.com/questions/3437059/does-python-have-a-string-contains-method) – khelwood Dec 19 '14 at 20:03

3 Answers3

8

Use in to test if one string is a substring of another.

>>> "www.example.com" in "http://www.example.com/aaa/bbb/ccc"
True
Kevin
  • 74,910
  • 12
  • 133
  • 166
  • 1
    Okay thanks! It was this simple! I was actually trying to use a a.find(b) method which dint work! – hnvasa Dec 19 '14 at 20:07
1

I'm showing another way to do this

>>> data = "http://www.example.com/aaa/bbb/ccc"
>>> key = "www.example.com"

>>> if key in data:
...     #do your action here
Raihan
  • 161
  • 2
  • 4
0

There are number of ways to do it:

>>> a = "http://www.example.com/aaa/bbb/ccc"
>>> b = "www.example.com"
>>> if a.find(b) >=0:            # find return position of string if found else -1
...     print(True)
... 
True
>>> import re
>>> if re.search(b,a):              
...     print(True)
... 
True
Hackaholic
  • 19,069
  • 5
  • 54
  • 72