個人博客首頁(點擊查看詳情) -- https://blog.51cto.com/11495268
個人微信公眾號(點擊查看掃描關注) -- https://blog.51cto.com/11495268/2401194

1、簡介

????字符串 相關操作 較多,本文 只簡單描述下 python 字符串 查找 相關的基礎操作
????

2、字符串 查找 內置函數

python 字符串 查找 基本操作_第1張圖片

3、實例

????獲取 指定 公司 的相關信息(公司信息 格式 都一致)

????

3.1 字符串 格式

            
              ## 公司名:排名:薪資-所占比例
HUAWEI:0:20K-30.8% ZTE:1:15K-50.6% SUNING:3:13K:39.9%
            
          

????

3.2 偽代碼(思路)

            
              查找 公司名 所在位置
從 公司名位置開始 查找 第一個 冒號 所在位置
從第一個 冒號 所在位置開始 查找 第二個 冒號 所在位置
從第二個 冒號 所在位置開始 查找 第一個 -號 所在位置
從第一個 -號 所在位置開始 查找 最近一個 空格 所在位置
    若 沒有 找到 最近一個 空格位置,那么 字符串長度 代表 索要獲取的位置(字符串結尾)
            
          

????

3.3 代碼

            
              #! /usr/bin/env python2.7
#-*- coding: utf-8-*.

str = 'SUNING'
string = 'HUAWEI:0:20K-30.8% ZTE:1:15K-50.6% SUNING:3:13K-39.9%'
index_company = string.find(str, 0, len(string))
index_first = string.find(':', index_company, len(string))
index_sec = string.find(':', index_first + 1, len(string))
index_line = string.find('-', index_sec + 1, len(string))
index_null = string.find(' ', index_line + 1, len(string))
if index_null == -1 :
    index_null = len(string)
# print 'index_company:%d,index_first:%d,index_sec:%d,index_line:%d,index_null:%d\n' % (index_company,index_first,index_sec,index_line,index_null)

print '公司名:%s\t\n' % (string[(index_company):(index_first)])
print '公司排名:%s\t\n' % (string[(index_first + 1):(index_sec)])
print '公司平均薪資:%s\t\n' % (string[(index_sec + 1):(index_line)])
print '公司平均薪資所占百分比:%s\t\n' % (string[(index_line + 1):index_null])
            
          

????

3.4 執行結果

python 字符串 查找 基本操作_第2張圖片

            
              # python str_find_wl.py 
index_company:35,index_first:41,index_sec:43,index_line:47,index_null:53

公司名:SUNING  

公司排名:3  

公司平均薪資:13K  

公司平均薪資所占百分比:39.9%