1

I am trying to see if a string contains certain text and if so do something, i have been using python's in operator, but i realized its too strict basically i have the following code

Usually this would return True

dynamic = "v23434"
filename = "v23434.jpg"

if dynamic in filename: return True

however, if i have

dynamic = "v23434-"
filename = "v23434.jpg"

then it returns False, due to the dash at the end of dynamic, so my question is, is there a way to check if the string filename has the string dynamic, but in a way that it doesn't have to be a perfect match, a few characters is enough.

EDIT

By a few characters, i mean a substring made up of the first 3 characters in dynamic, so if i have

dynamic = "v23434-"
filename = "testingv23434.jpg"

then it should match, because the substring "v23" is found inside filename

Paulo
  • 6,982
  • 7
  • 42
  • 56
  • 3
    Well, how do you define "a few characters"? How do you define an imperfect match? Do you need the _first_ few (and how many?) characters of `dynamic` to be found in `filename`, or are you looking for _any_ substring of `dynamic` that occurs in `filename`? Possibly with some minimum length? There are algorithms to solve all these problems, but you have to be specific about what your requirements are. – David Z Feb 06 '12 at 21:35
  • 2
    See [this](http://stackoverflow.com/q/682367/566644) question. – Lauritz V. Thaulow Feb 06 '12 at 21:36
  • 1
    you could use stuff like Levenshtein distance – ptitpoulpe Feb 06 '12 at 21:37
  • @david i edited the question to be more specific, thank you for your input – Paulo Feb 06 '12 at 21:44

4 Answers4

3

If you just want to test the first three characters in your search term, then use

def test(dynamic, filename):
    return dynamic[:3] in filename
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
1

Just slice off the first three characters of the one string:

if dynamic[:3] in filename
kurosch
  • 2,292
  • 16
  • 17
1

This bit of code will help with your issue i you are looking for at least 3 consecutive chars:

>>> dynamic = "v23434-"
>>> filename = "testingv23434.jpg"
>>> any( s in filename for s in [ dynamic[i:i+3] for i in range( 0, len(dynamic)-2 ) ] )
True

>>> filename = "testingv334.jpg"
>>> any( s in filename for s in [ dynamic[i:i+3] for i in range( 0, len(dynamic)-2 ) ] )
False
dani herrera
  • 48,760
  • 8
  • 117
  • 177
0

You need edit distances: http://www.mindrot.org/projects/py-editdist/

Sid
  • 7,511
  • 2
  • 28
  • 41