温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

python 字符串 查找 基本操作

发布时间:2020-07-29 22:02:19 来源:网络 阅读:407 作者:坚韧的石头 栏目:编程语言

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

1、简介

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

2、字符串 查找 内置函数

python 字符串 查找 基本操作

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 字符串 查找 基本操作

# 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%   
向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI