python实现从字符串中找出字符1的位置以及个数的方法

yipeiwu_com6年前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中的Numpy、SciPy、MatPlotLib安装与配置

详解Python中的Numpy、SciPy、MatPlotLib安装与配置

用Python来编写机器学习方面的代码是相当简单的,因为Python下有很多关于机器学习的库。其中下面三个库numpy,scipy,matplotlib,scikit-learn是常用组...

python 异常处理总结

       最近,做个小项目经常会遇到Python 的异常,让人非常头疼,故对异常进行整理,避免下次遇到异常不知所措,以下就...

python+opencv实现车牌定位功能(实例代码)

python+opencv实现车牌定位功能(实例代码)

写在前面 HIT大三上学期视听觉信号处理课程中视觉部分的实验三,经过和学长们实验的对比发现每一级实验要求都不一样,因此这里标明了是2019年秋季学期的视觉实验三。 由于时间紧张,代码没有...

Cython 三分钟入门教程

作者:perrygeo译者:赖勇浩(http://laiyonghao.com/)原文:http://www.perrygeo.net/wordpress/?p=116 我最喜欢的是Py...

从pandas一个单元格的字符串中提取字符串方式

以titanic数据集为例。 其中name列是字符串,现在想从其中提取title作为新的一列。 例如: # create new Title column df['Title'] =...