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脚本实现集群检测和管理功能

Python脚本实现集群检测和管理功能

场景是这样的:一个生产机房,会有很多的测试机器和生产机器(也就是30台左右吧),由于管理较为混乱导致了哪台机器有人用、哪台机器没人用都不清楚,从而产生了一个想法--利用一台机器来管理所有...

解决pycharm remote deployment 配置的问题

解决pycharm remote deployment 配置的问题

(1)无法完整识别服务器端的环境变量 举例: a: shell下 b:win7下使用pycharm 结果发现对应的环境变量值缺失 如此会影响一些模块的正常加载(如cx_Oracle需...

Python FTP两个文件夹间的同步实例代码

具体代码如下所示: # -*- coding: utf-8 -*- ''''''' ftp自动检测源文件夹的更新,将源文件夹更新的内容拷贝到目标文件夹中 使用树的层序遍...

python matplotlib画图库学习绘制常用的图

python matplotlib画图库学习绘制常用的图

本文实例为大家分享了python matplotlib绘制常用图的具体代码,供大家参考,具体内容如下 github地址 导入相关类 import numpy as np import...

详解Python给照片换底色(蓝底换红底)

详解Python给照片换底色(蓝底换红底)

现在网上出现了很多在线换底色的网页版工具是这么做的呢?其实用Python就可以实现。 环境要求 Python3 numpy函数库 opencv库 安装 下载适应版本的numpy函数库...