python - 在Python中查找特定的字符串部分

标签 python string indexing

我希望能够使用函数抓取字符串部分。这是一个例子:

def get_sec(s1,s2,first='{',last='}'):
    start = s2.index(first)
    end = -(len(s2) - s2.index(last)) + 1
    a = "".join(s2.split(first + last))
    b = s1[:start] + s1[end:]
    print a
    print b
    if a == b:
        return s1[start:end] 
    else:
        print "The strings did not match up"
string = 'contentonemore'
finder = 'content{}more'
print get_sec(string,finder)
#'one'

所以这个例子有效......我的问题是我想要多个部分,而不仅仅是一个。所以我的函数需要能够适用于任意数量的部分,例如:

test_str = 'contwotentonemorethree'
test_find = 'con{}tent{}more{}'
print get_sec(test_str,test_find)
#['one','two','three']

关于如何使该函数适用于任意数量的替换,有什么想法吗?

最佳答案

您可能想使用标准 python regex图书馆

import re
a = re.search('con(.*)tent(.*)more(.*)','contwotentonemorethree')
print a.groups()
# ('two', 'one', 'three')

或者 print re.findall('con(.)tent(.)more(.*)','contwotentonemorethird') # [('二', '一', '三')]

编辑:
您可以使用转义字符串中的特殊字符

re.escape(str)

示例:

part1 = re.escape('con(')
part2 = re.escape('(tent')
print re.findall(part1 + '(.*)' + part2,'con(two)tent')

关于python - 在Python中查找特定的字符串部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17158676/

相关文章:

python - 如何避免带有包含 os.system 调用的 .pyw 文件的控制台窗口?

python - 如何加载保存为 .pb 的 keras 模型

Python程序不循环/重新启动

javascript - 正则表达式删除 javascript 中字符串开头和结尾的所有 <br/> 标签

mysql - 如何优化 MySQL 索引/查询以进行模块化搜索?

python - mongokit 索引不起作用

python - 子类别 Django 商店

c# - String.Intern 和 String.IsInterned 有什么区别?

javascript - 如何将文本字符串拆分为多个部分?

MongoDB 索引用于查找和排序