Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

startswith and re.search^ in python

# 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()
Source by www.py4e.com #
 
PREVIOUS NEXT
Tagged: #startswith #python
ADD COMMENT
Topic
Name
7+1 =