如何在python中获取子字符串索引

时间:2018-08-16 17:07:56

标签: python regex

substring_list = [“拥有”,“必须”,“加”,“必须”]

mystr ='''C ++ C,标准模板库,IOStreams,字符串库和C ++标准容器,C库 C ++,C#,Microsoft .NET框架,Winforms,WPF,Infragistics,T​​FS 跨语言集成,REST 必须非常熟悉Oracle数据库SQL的现代版本。 拥有Core Java,Collections,多线程,Spring,JSON很好。 高超的交流技巧。 熟悉现代的完整软件开发生命周期实践'''

对于substring_list中的w:

如何获取子字符串的索引

3 个答案:

答案 0 :(得分:0)

您可以尝试

for x in substring_list:
    y = mystr.find(x)
    if y != -1:
        print("found: ", x, "at ", y)

输出

  

('找到了','拥有的好','在',271)

有关find HERE

的更多信息

答案 1 :(得分:0)

mystr.find(w)

这将返回找到的子字符串的第一个实例的索引;如果未找到子字符串,则返回-1。例如,对于第一个子字符串,它将返回271。您可以使用mystr[271:]检索位于该索引上的字符串。

答案 2 :(得分:0)

您必须遍历列表,找到开始和结束位置,然后显示。您可以以此为基础。

    substring_list = ['good to have', 'must have','plus','must']

    mystr = "C++ C, Standard Template Library, IOStreams, String Library and C++ Standard containers, the C Library C++, C#, Microsoft .NET frameworks, Winforms, WPF, Infragistics, TFS Inter-language integration, REST Must be very familiar with modern versions of Oracle databas SQL. good to have Core Java, Collections, multi-threading, Spring, JSON. Excellent communication skills. Familiarity with modern full software development lifecycle practices"

    for i in substring_list:
        if i in mystr:
            start=mystr.find(i)
            end=start + len(i)
            print('Substring found: "%s" Start: %s End %s' %(mystr[start:end], start, end))
        else:
            print('Substring not found: "%s" ' %(i))

输出如下:

     Substring found: "good to have" Start: 271 End 283
     Substring not found: "must have"
     Substring not found: "plus"
     Substring not found: "must"