strthon中的strncmp

R11*_*R11 10 python

我正在解析带有路径列表的文件.我试图查看一个路径是否在特定目录下.所以我有两个字符串S1和S2.让我们说它们是S1 ='/ tmp /'和S2 ='/ tmp/file.txt'

如果我想检查S2是否有S1然后在C中有一些额外的字节,我会做一个S1和S2的strncmp到strlen(S1)字节.有没有办法在python中做到这一点?我是python的新手,并不知道我可用的所有模块.我可以通过迭代字符串中的字符并进行比较来实现这一点,但是想知道是否有任何东西在默认情况下给我这些辅助函数

谢谢你的帮助.

P

mgi*_*son 13

是.你可以这样做: if a in b: 那将检查是否a是任何地方的子字符串b.

例如

if 'foo' in 'foobar':
    print True

if 'foo' in 'barfoo':
    print True
Run Code Online (Sandbox Code Playgroud)

从您的帖子看,您似乎只想查看字符串的开头.在这种情况下,您可以使用以下.startswith方法:

if 'foobar'.startswith('foo'):
    print "it does!"
Run Code Online (Sandbox Code Playgroud)

同样,你也可以做同样的事情endswith:

if 'foobar'.endswith('bar'):
    print "Yes sir :)"
Run Code Online (Sandbox Code Playgroud)

最后,也许最直接的翻译strncmp是使用切片和==:

if a[:n] == b[:n]:
    print 'strncmp success!'
Run Code Online (Sandbox Code Playgroud)

Python还有许多用于处理os.path模块中路径名的工具.值得调查那里的内容.有一些很漂亮的功能.


rgr*_*erg 5

您可能正在寻找os.path.commonprefix

例如:os.path.commonprefix(['/tmp/','/tmp/file.txt'])将返回'/tmp/

所以你应该检查 len(os.path.commonprefix([s1,s2])) > 0

在此处查看文档:http : //docs.python.org/2/library/os.path.html