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

WBOY
Release: 2016-06-16 08:42:32
Original
1636 people have browsed it

本文实例主要实现给出任意字符串,获取字符串中某字符的位置以及出现的总次数。

实现该功能代码的时候可以使用函数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)  
Copy after login

希望本文实例对大家Python程序设计中字符串操作的学习有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!