In this article, the main example of the implementation of an arbitrary string, to obtain the location of a character in the string and the total number of occurrences.
The realization of the function of the code can use the function enumerate to separate the string into position and character, and then compare can be.
The specific implementation code is as follows:
#!/bin/env python #-*- coding:utf-8 -*- # """ Find all the 1's in the string with enumerate, the Implement with 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)
I hope that the examples in this article will help you to learn string manipulation in Python programming.