Python字符串中查找子串小技巧

yipeiwu_com6年前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])

相关文章

Python实现模拟时钟代码推荐

Python实现模拟时钟代码推荐 # coding=utf8 import sys, pygame, math, random from pygame.locals import *...

Python读写unicode文件的方法

本文实例讲述了Python读写unicode文件的方法。分享给大家供大家参考。具体实现方法如下: #coding=utf-8 import os import codecs d...

python 读取文本文件的行数据,文件.splitlines()的方法

一般跟踪训练的ground_truth的数据保存在文本文文件中,故每一行的数据为一张图片的标签数据,这个时候读取每一张图片的标签,具体实现如下: test_txt = '/home/...

AI人工智能 Python实现人机对话

AI人工智能 Python实现人机对话

在人工智能进展的如火如荼的今天,我们如果不尝试去接触新鲜事物,马上就要被世界淘汰啦~ 本文拟使用Python开发语言实现类似于WIndows平台的“小娜”,或者是IOS下的“Siri”。...

pip 错误unused-command-line-argument-hard-error-in-future解决办法

在我的Mac Air上,用pip安装一些Python库时,偶尔就会遇到一些报错,关于“unused-command-line-argument-hard-error-in-future”...