200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python字符串怎么查找_python 字符串 查找 基本操作

python字符串怎么查找_python 字符串 查找 基本操作

时间:2023-03-17 15:17:31

相关推荐

python字符串怎么查找_python 字符串 查找 基本操作

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%

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。