码迷,mamicode.com
首页 > 编程语言 > 详细

python 字符串 查找 基本操作

时间:2019-06-25 19:48:41      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:info   第一个   公众号   实例   字符串   fir   简单   信息   first   

个人博客首页(点击查看详情) -- https://blog.51cto.com/11495268
个人微信公众号(点击查看扫描关注) -- https://blog.51cto.com/11495268/2401194

1、简介

????字符串 相关操作 较多,本文 只简单描述下 python 字符串 查找 相关的基础操作
????

2、字符串 查找 内置函数

技术图片

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 str_find_wl.py 
index_company:35,index_first:41,index_sec:43,index_line:47,index_null:53

公司名:SUNING  

公司排名:3  

公司平均薪资:13K  

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

python 字符串 查找 基本操作

标签:info   第一个   公众号   实例   字符串   fir   简单   信息   first   

原文地址:https://blog.51cto.com/11495268/2413492

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!