Search For A String in Python-Exp-5
Search For A String in Python-Exp-5
If you want to search the contents of a text file, read the file as a
string.
print('sam' in s)
# False
Note that the in operator can also be used for lists, tuples, and
dictionaries. See the following article for details.
The in operator in Python (for list, string, dictionary, etc.)
Get the position (index) of a given
substring: find(), rfind()
You can get the position of a given substring in the string with
the find() method of str.
Built-in Types - str.find() — Python 3.11.3 documentation
If the substring specified as the first argument is found, the method
returns its starting position (the position of the first character); if
not found, -1 is returned.
s = 'I am Sam'
print(s.find('Sam'))
# 5
print(s.find('XXX'))
# -1
source: str_in_find_rfind.py
The rfind() method searches the string starting from the right side.
Built-in Types - str.rfind() — Python 3.11.3 documentation
If multiple substrings are present, the position of the rightmost
substring is returned. Similar to find(), you can also
specify start and end arguments for the rfind() method.
print(s.rfind('am'))
# 6
print(s.rfind('XXX'))
# -1
print(s.rfind('am', 2))
# 6
print(s.rfind('am', 2, 5))
# 2
source: str_in_find_rfind.py
# print(s.index('XXX'))
# ValueError: substring not found
print(s.rindex('am'))
# 6
# print(s.rindex('XXX'))
# ValueError: substring not found
source: str_in_find_rfind.py
Case-insensitive search
Note that the in operator and the string methods mentioned so far
are case-sensitive.
For case-insensitive searches, you can convert both the search
string and target string to uppercase or lowercase. Use
the upper() method to convert a string to uppercase, and
the lower() method to convert it to lowercase.
Uppercase and lowercase strings in Python (conversion and
checking)
s = 'I am Sam'
print(s.upper())
# I AM SAM
print(s.lower())
# i am sam
print('sam' in s)
# False
print('sam' in s.lower())
# True
print(s.find('sam'))
# -1
print(s.lower().find('sam'))
# 5
s = 'I am Sam'
print(re.search('Sam', s))
# <re.Match object; span=(5, 8), match='Sam'>
print(re.search('XXX', s))
# None
source: str_search_regex.py
You can get various information with the methods of the match
object.
print(m.group())
# Sam
print(m.start())
# 5
print(m.end())
# 8
print(m.span())
# (5, 8)
print(re.search('am', s))
# <re.Match object; span=(2, 4), match='am'>
print(re.findall('Sam|Adams', s))
# ['Sam', 'Adams']
print([m.span() for m in re.finditer('Sam|Adams', s)])
# [(5, 8), (9, 14)]
source: str_search_regex.py
print(re.findall('am', s))
# ['am', 'am', 'am']
print(re.findall('[a-zA-Z]+am[a-z]*', s))
# ['Sam', 'Adams']
print(re.search('sam', s))
# None
print(re.search('sam', s, flags=re.IGNORECASE))
# <re.Match object; span=(5, 8), match='Sam'>