R11
R11

Reputation: 415

strncmp in python

I am parsing through a file with a list of paths. I am trying to see if one path is under a specific directory or not. So I have two strings: S1 = '/tmp/' and S2 = '/tmp/file.txt'

If I want to check if S2 contains S1 plus some extra bytes, in C, I would do a strncmp of S1 and S2 upto strlen(S1) bytes. Is there a way to do that in Python? I am new to Python and do not know all the modules available to me yet. I could implement this trivially by just iterating over the characters in the strings and comparing, but want to find out if there is anything that gives me these kind of helper functions by default

Upvotes: 11

Views: 65916

Answers (4)

mgilson
mgilson

Reputation: 310167

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.

Upvotes: 16

Jiangzhou
Jiangzhou

Reputation: 173

You can test that by

S2[:len(S1)] == S1

or even simpler:

S2.startswith(S1)

Upvotes: 1

Ali-Akber Saifee
Ali-Akber Saifee

Reputation: 4616

you can use the find method of a string

>>> s1 = "/tmp"
>>> s2 = "/tmp/file.txt"
>>> s2.find(s1)
0

Upvotes: 0

rgrinberg
rgrinberg

Reputation: 9878

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

Upvotes: 5

Related Questions