How do you find all occurrences of a character in a string in python?
I am trying to find all the occurences of "|" in a string. Show
But I get an error:
asked Oct 22, 2012 at 10:39
2
The function:
will return a list of the indices of
Mooncrater 3,5444 gold badges26 silver badges53 bronze badges answered Oct 22, 2012 at 10:50
Marco L.Marco L. 1,4794 gold badges17 silver badges25 bronze badges 3 if you want index of all occurrences of
also you can do
answered Oct 22, 2012 at 10:45
avasalavasal 13.8k4 gold badges30 silver badges47 bronze badges It is easier to use regular expressions here;
answered Oct 22, 2012 at 10:56
Roland SmithRoland Smith 40.6k3 gold badges58 silver badges87 bronze badges
dbr 161k65 gold badges273 silver badges339 bronze badges answered Oct 22, 2012 at 10:57
ZuluZulu 8,0599 gold badges46 silver badges55 bronze badges
I suggest:
answered Oct 22, 2012 at 10:48
samfrancessamfrances 2,9753 gold badges24 silver badges36 bronze badges 1 If
Note: This will also work for searching sub-strings. answered Aug 30, 2018 at 7:26
Pablo ReyesPablo Reyes 2,92919 silver badges29 bronze badges text.find() only returns the first result, and then you need to set the new starting position based on that. So like this:
answered Oct 22, 2012 at 10:48
M SomervilleM Somerville 4,33727 silver badges37 bronze badges 2 How do you find the occurrences of a string in a string Python?The count() method returns the number of occurrences of a substring in the given string.. substring - string whose count is to be found.. start (Optional) - starting index within the string where search starts.. end (Optional) - ending index within the string where search ends.. How do you find all instances of a character in a string?1. Using indexOf() and lastIndexOf() method. The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.
Which method finds the list of all occurrences of the pattern in the given string?finditer() To get all occurrences of a pattern in a given string, you can use the regular expression method re. finditer(pattern, string) . The result is an iterable of match objects—you can retrieve the indices of the match using the match.
How do you count repeated letters in Python?Python. string = "Great responsibility";. print("Duplicate characters in a given string: ");. #Counts each character present in the string.. for i in range(0, len(string)):. count = 1;. for j in range(i+1, len(string)):. if(string[i] == string[j] and string[i] != ' '):. count = count + 1;. |