String Library
String Replace
str="Hello Bob"
print(str)
rstr=str.replace('Bob', 'James')
print(rstr)
This will replace the Bob with James and store it in the new variable. The variable ‘str’ will remain the same.
Strip or lstrip
str=" Hello Bob"
str.lstrip()
“Hello Bob” – spaces removed from the left
str="Hello Bob "
str.rstrip()
“Hello Bob” – spaces removed from the right
str=" Hello Bob "
str.strip()
“Hello Bob” – spaces removed from the left and right, also removes the ‘\n’ new line character from the end of the string.
Prefixes
line='Please take a sip of coffee'
line.startswith('Please')
True
line.startswith('P')
True
line.startswith('p')
False
Parsing and Extracting
Extracting data from an email ID required to search the letter ‘@’ then search the keyword ‘>’, then print the values between them. The below find function provides you the position of the
data= 'From Dr. Suyash Bhardwaj <suyash.bhardwaj@gkv.ac.in>'
at=data.find('@')
print(at)
41
great=data.find('>',at)
print(great)
31
domain=data[at+1:great]
print(domain)
gkv.ac.in