Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

Find All Occurrences of a Substring in a String in Python

import re 
 
# defining string  
str1 = "This dress looks good; you have good taste in clothes."
 
#defining substring 
substr = "good"
 
print("The original string is: " + str1) 
 
print("The substring to find: " + substr) 
 
result = [_.start() for _ in re.finditer(substr, str1)] 
 
print("The start indices of the substrings are : " + str(result))

# Output - 
# The original string is: This dress looks good; you have good taste in clothes.
# The substring to find: good
# The start indices of the substrings are : [17, 34]
Comment

Find All Occurrences of a Substring in a String in Python

#defining string and substring
str1 = "This dress looks good; you have good taste in clothes."
substr = "good"

#occurrence of word 'good' in whole string
count1 = str1.count(substr)
print(count1)

#occurrence of word 'good' from index 0 to 25
count2 = str1.count(substr,0,25)
print(count2)

# output -
# 2
# 1
Comment

PREVIOUS NEXT
Code Example
Python :: match python 3.10 
Python :: custom position for axis matplotlib 
Python :: python thousands separators 
Python :: separating tuple in pandas 
Python :: convert csv file into python list 
Python :: huggingface transformers change download path 
Python :: read file csv in python 
Python :: python filter timestamp 
Python :: Game of Piles Version 2 
Python :: django environment variables 
Python :: read a file python 
Python :: seaborn pink green color palette python 
Python :: How to join train and Test dataset in python 
Python :: how to make convert numpy array to string in python 
Python :: np array to list 
Python :: not null constraint failed django 
Python :: pip install django celery results 
Python :: numpy random matrix 
Python :: how to define piecewise function i python 
Python :: python variable 
Python :: how to put legend outside pie plot in python 
Python :: get last 3 in list python 
Python :: remove item list python 
Python :: disbale tkinter textbox 
Python :: python how to show package version 
Python :: fibonacci series using recursion in python 
Python :: how to take multiple line inputs in python 
Python :: python user input to tuple 
Python :: python list pop vs remove 
Python :: pandas group by include nan 
ADD CONTENT
Topic
Content
Source link
Name
2+4 =