import re
if re.match(r'^hello', somestring):
# do stuff
# This is how we use startswith
# Open a file
hand = open('Path and the name of the file')
count1 = 0
for line in hand:
# remove new line (/n) at the end of the line
line = line.rstrip()
# If there is the 'sub string' at the beginning of the line it will give True
if line.startswith('Substring'):
count1 += 1
print(count1, line)
# Close the file
hand.close()
# This is how we use re.search with carrot sign ^
# This means match the beginning of the line
import re
count2 = 0
hand2 = open('Path and the name of the file')
for line2 in hand2:
# remove new line (/n) at the end of the line
line2 = line2.rstrip()
# before the substring you need to type ^
if re.search('^substring', line2):
count2 += 1
print(count2, line2)
# Close the file
hand2.close()