python实现从字符串中找出字符1的位置以及个数的方法,python字符串
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程序设计中字符串操作的学习有所帮助。
def f(s, c):
count = 0
while len(s) > 0:
index = s.find(c)
if index == -1:
break
count += 1
s = s[index+len(c):]
return count
def g(s, c):
cs = ""
while True:
cs += c
count = f(s, cs)
if count > 0:
print count, cs
else:
break
a="123456789011112221111111122211111111"
g(a, "1")
结果:
21 1
10 11
5 111
5 1111
2 11111
2 111111
2 1111111
2 11111111
也可以用re模块做.
用re吧
>>> import re>>> word = "test">>> s = "test abcd test 1234 testcase testsuite">>> [m.start() for m in re.finditer(word, s)][0, 10, 20, 29]
相关内容
- python3编写C/S网络程序实例教程,python3实例教程
- python常用web框架简单性能测试结果分享(包含django、fl
- Python3.0与2.X版本的区别实例分析,python3.02.x
- Python实现多行注释的另类方法,python多行
- Python升级提示Tkinter模块找不到的解决方法,pythontkint
- python错误:AttributeError: 'module' object has no attribute 'setd
- Python中还原JavaScript的escape函数编码后字符串的方法,
- python with statement 进行文件操作指南,
- Python with的用法,Pythonwith用法
- Python安装Imaging报错:The _imaging C module is not installed问题
评论关闭