Python implements a method for finding the position and number of the character 1 in a string

  • 2020-04-02 14:00:29
  • OfStack

The main implementation of this example is to give an arbitrary string, get the position of a character in the string and the total number of occurrences.

You can use the function enumerate to separate strings into positions and characters and then compare them.

The specific implementation code is as follows:


#!/bin/env python
#-*- coding:utf-8 -*-
#
"""
   with enumerate will string In the 1 To find out all ,
   with enumerate Implementation: 
"""
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)  

I hope this example has helped you learn about string manipulation in Python programming.


Related articles: