strncmp in python

Yes. You can do: if a in b: That will check if a is a substring anywhere in b.

e.g.

if 'foo' in 'foobar':
    print True

if 'foo' in 'barfoo':
    print True

From your post, it appears you want to only look at the start of the strings. In that case, you can use the .startswith method:

if 'foobar'.startswith('foo'):
    print "it does!"

Similarly, you can do the same thing with endswith:

if 'foobar'.endswith('bar'):
    print "Yes sir :)"

finally, maybe the most literal translation of strncmp would be to use slicing and ==:

if a[:n] == b[:n]:
    print 'strncmp success!'

Python also has many facilities for dealing with path names in the os.path module. It's worth investigating what is in there. There are some pretty neat functions.


You're probably looking for os.path.commonprefix.

for example: os.path.commonprefix(['/tmp/','/tmp/file.txt']) will return '/tmp/

so you should check for len(os.path.commonprefix([s1,s2])) > 0

Check out docs here: http://docs.python.org/2/library/os.path.html

Tags:

Python