Given the following Python code: import re text = "IBPS_SO_IT_2024" result =…
2024
Given the following Python code:
import re
text = "IBPS_SO_IT_2024"
result = re.findall(r'[A-Z]+', text)
print(result[1])What will be the output of the above code?
- A.
IBPS - B.
SO - C.
IT - D.
2024 - E.
_
Attempted by 25 students.
Show answer & explanation
Correct answer: B
Concept
re.findall(pattern, text) scans the whole string left to right and returns a list of every non-overlapping match, in the order they occur. The class [A-Z]+ matches one or more consecutive uppercase letters (A–Z) as a single maximal run; any character that is not an uppercase letter (an underscore, a digit, a lowercase letter) ends the current run and is itself skipped. Python lists are zero-indexed, so result[1] is the second element.
Application
Scan "IBPS_SO_IT_2024" run by run:
"IBPS" is a run of uppercase letters; the following "_" breaks it — first match.
"SO" is the next uppercase run; the following "_" breaks it — second match.
"IT" is the next uppercase run; the following "_" breaks it — third match.
The trailing "2024" is all digits, so
[A-Z]+finds nothing there.
The returned list is ['IBPS', 'SO', 'IT'].
Cross-check
Indexing the list: result[0] = "IBPS", result[1] = "SO", result[2] = "IT". The program prints result[1], the second element, so the output is SO.