Python implements a method of finding the position and number of characters 1 from a string _python

Source: Internet
Author: User
Tags in python

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

When implementing this feature code, you can use 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 to find out 1 of the string,
  with the 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 (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 (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 will help you learn about string manipulation in Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.