Professional Documents
Culture Documents
PRACTICAL – 11
1. For the given input list, filter all elements that contains 42 surrounded by word characters.
>>> words = ['hi42bye', 'nice1423', 'bad42', 'cool_42a', 'fake4b']
CODE –
import re
words = ['hi42bye', 'nice1423', 'bad42', 'cool_42a', 'fake4b']
for value in words:
match = re.search(r'\w*42\w*', value)
if match:
print(match.group())
OUTPUT –
FP 1
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
2. For the given input string, change whole word mall to 1234 only if it is at the
start of a line.
>>> para = '''\
... ball fall wall tall
... mall call ball pall
... wall mall ball fall
... mallet wallet malls'''
CODE –
import re
words = '''\
... ball fall wall tall
... mall call ball pall
... wall mall ball fall
... mallet wallet malls'''
print("-------------------")
OUTPUT –
FP 2
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
3. For the given input list, filter all elements starting with h. Additionally,
replace e with X for these filtered elements.
>>> items = ['handed', 'hand', 'handy', 'unhanded', 'handle', 'hand-2']
CODE –
import re
OUTPUT –
FP 3
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
OUTPUT –
FP 4
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
5. For the given input strings, remove everything from the first occurrence of i till
end of the string.
>>> s1 = 'remove the special meaning of such constructs'
>>> s2 = 'characters while constructing'
CODE –
import re
pat = re.compile(r'i.*')
print(pat.sub('', s1))
print(pat.sub('', s2))
OUTPUT –
FP 5
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
6. Find the starting index of first occurrence of is or the or was or to for the given
input strings.
>>> s1 = 'match after the last newline character'
>>> s2 = 'and then you want to test'
>>> s3 = 'this is good bye then'
>>> s4 = 'who was there to see?'
CODE –
import re
pat = re.compile(r'is|the|was|to')
print(pat.search(s1).start())
print(pat.search(s2).start())
print(pat.search(s3).start())
print(pat.search(s4).start())
OUTPUT –
FP 6
VRAJ PATEL (20162171034)(CS) PRACTICAL - 11
7. You are given stock prices for related financial tickers. (Symbols representing
companies in the stock market)
Find a way to extract the tickers mentioned in the report.
i.e.: TSLA, NFLX ...
str="Some of the prices were as following TSLA:749.50, ORCL: 50.50, GE:
10.90, MSFT: 170.50, BIDU: 121.40. As the macroeconomic developments
continue we will update the prices. "
CODE –
import re
str = """Some of the prices were as following TSLA:749.50, ORCL: 50.50, GE: 10.90,
MSFT: 170.50, BIDU: 121.40. As the macroeconomic developments continue we will update
the prices. """
regex = r'[A-Z]{2,}'
data = re.findall(regex, str)
print(data)
OUTPUT –
FP 7