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
strcmp compares both the strings till null-character of either string comes whereas strncmp compares at most num characters of both strings. But if num is equal to the length of either string than strncmp behaves similar to strcmp.
Presuming that the string in message is supposed to be null-terminated, the only reason to use strncmp() here rather than strcmp() would be to be to prevent it looking beyond the end of message , in the case where message is not null-terminated.
Python String comparison can be performed using equality (==) and comparison (<, >, != , <=, >=) operators. There are no special methods to compare two strings.
Consequences are unlikely to happen in strcmp, but issue is the same. strnxxx function family try to prevent reading/writing not acquired memory. Disadvantage of using strn is extra compare and decrement operation on counter. In few words: strncmp is safer then strcmp, but it is slower too.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With