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.