Python uses the string to find the position and number of characters 1.

Source: Internet
Author: User
This article mainly introduces how to find the position and number of character 1 from a string in python, which is helpful for learning Python string operations, you can refer to the example in this article to obtain the position of a character in the string and the total number of times it appears.

When implementing this function code, you can use the function enumerate to separate the string into positions and characters and then compare them.

The specific implementation code is as follows:

#! /Bin/env python #-*-coding: UTF-8-*-# "use enumerate to find all 1 in string, and use enumerate to implement: "" def get_1_pos (string): onePos = [] try: onePos = list (pos, int (val) for pos, val in enumerate (string) if val = '1') rows T: pass return onePosdef 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): pass return chPosdef 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 article will help you learn about string operations in Python programming.

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.