Python小技巧 - 子串查找

惭愧啊,今天写了个查找子串的Python程序被BS了…

如果让你写一个程序检查字符串s2中是不是包含有s1。也许你会很直观的写下下面的代码:

#determine whether s1 is a substring of s2 
def isSubstring1(s1,s2): 
    tag = False 
    len1 = len(s1) 
    len2 = len(s2) 
    for i in range(0,len2): 
        if s2[i] == s1[0]: 
            for j in range(0,len1): 
                if s2[i]==s1[j]: 
                    tag = True 
    return tag

 

可是这是Python,我们可以利用字符串自带的find()方法,于是可以这样:

def isSubstring2(s1,s2): 
    tag = False 
    if s2.find(s1) != -1: 
        tag = True 
    return tag

悲情的事就在于此,原来Python中的关键字"in”不仅可以用于列表、元祖等数据类型,还可以用于字符串。所以,这里只需要直接一行代码搞定:

def isSubstring3(s1,s2):
    return s1 in s2

后知后觉了,惭愧;-)

类似的,假设要在字符串中,查找多个子串是否存在,并打印出这些串和首次出现的位置:

def findSubstrings(substrings,destString):
    res =  map(lambda x:str([destString.index(x),x]),filter(lambda x:x in destString,substrings))
    if res:
        return ', '.join(list(res))
 
;-)  very cool~
UPDATE: 如果你不习惯最后面这种看起来很复杂的语法也没关系,可以使用列表解析,更加简洁:
def findSubstrings(substrings,destString):
    
return ''.join([str([destString.index(x),x]) for x in substrings if x in destString])
 

 

 
posted @ 2010-03-03 22:54 Freesc Huang 阅读(1118) 评论(1) 编辑
<2010年3月>
28123456
78910111213
14151617181920
21222324252627
28293031123
45678910

公告

These postings are provided "AS IS" with no warranties
and confer no rights.


Locations of visitors to this page

Blog Keywords
Embedded System,Visual Studio,.Net Framework,.Net Compact Framework,.Net Micro Framework,Windows Mobile,Windows Embedded CE,Emulator,WCF,CLR,Design & Pattern,C/C++,C#,Matlab,Algorithms
昵称:Freesc Huang
园龄:4年11个月
粉丝:32
关注:4

统计

  • 随笔 - 197
  • 文章 - 0
  • 评论 - 840

搜索

 

随笔分类(227)

随笔档案(197)

Blogs

Link

积分与排名

最新评论

阅读排行榜

评论排行榜

推荐排行榜