python实现从字符串中找出字符1的位置以及个数的方法
更新时间:2014年08月25日 10:30:10 投稿:shichen2014
这篇文章主要介绍了python实现从字符串中找出字符1的位置以及个数的方法,对于Python字符串操作的学习有一定的帮助与借鉴作用,需要的朋友可以参考下
本文实例主要实现给出任意字符串,获取字符串中某字符的位置以及出现的总次数。
实现该功能代码的时候可以使用函数enumerate来将字符串分离成位置和字符,然后进行比较即可。
具体实现代码如下:
#!/bin/env python #-*- coding:utf-8 -*- # """ 用enumerate将string中的1都找出来, 用enumerate实现: """ def get_1_pos(string): onePos=[] try: onePos=list(((pos,int(val)) for pos,val in enumerate(string) if val == '1')) except: pass return onePos def get_1_num(string): return len(list(get_1_pos(string))) def get_char_pos(string,char): chPos=[] try: chPos=list(((pos,char) for pos,val in enumerate(string) if(val == char))) except: pass return chPos def get_char_num(string,char): return len(list(get_char_pos(string,char))) if(__name__ == "__main__"): str0="10101010101010101" str1="123abc123abc123abc" lt=get_1_pos(str0) print(lt) lt=get_1_pos(str1) print(lt) num=get_1_num(str0) print(num) lt=get_char_pos(str1,'1') print(lt) num=get_char_num(str1,'1') print(num)
希望本文实例对大家Python程序设计中字符串操作的学习有所帮助。
相关文章
Python中time模块与datetime模块在使用中的不同之处
这篇文章主要介绍了Python中time模块与datetime模块在使用中的不同之处,是Python入门学习中的基础知识,需要的朋友可以参考下2015-11-11Python3爬虫学习之爬虫利器Beautiful Soup用法分析
这篇文章主要介绍了Python3爬虫学习之爬虫利器Beautiful Soup用法,结合实例形式分析了Beautiful Soup的功能、使用方法及相关操作注意事项,需要的朋友可以参考下2018-12-12python安装mysql的依赖包mysql-python操作
这篇文章主要介绍了python安装mysql的依赖包mysql-python操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧2021-01-01
最新评论