2. String is a class
An object of the string class will be created
Class is a collection of member variables and member functions
Python provides built-in set of member classes.
Accessed using dot operator
objName.memberMethod(arguments)
dir provides variables and methods of a class
String Methods and Files
3. Eg: s=‘Python’
type(s)
dir(s)
The methods are called using object name: Method Invocation
Eg: s=‘abc’
s.islower()
s=‘ABC’
s.islower()
5. 1. capitalize: Returns the capitalize version of the original string
Eg: s='hello'
s1=str.capitalize(s)
print(s1)
s='hello World'
print(s.capitalize())
#Hello world
s='hello World'
print(s.capitalize())
2. s.upper(): Returns a copy of string to uppercase.
Eg: s='hello‘
s1=s.upper()
print(s1)
6. 3. s.lower(): Returns the lower version of string
Eg: s='HELLO'
print(s.lower())
4. s.find(s1): Used to search for a substring. If found, return the index value else return the value as -1.
Eg: s='python'
print(s.find('o')) #4
s='python'
print(s.find('o')) #-1
The find function can take one or more arguments. Start and End
Eg: s='Calender is August'
s.find('Cal')
s.find('cal')
s.find('e',6,10)
7. 5. s.strip(): Returns a copy of string by removing leading (first) and trailing (last) whitespaces.
Eg: s=' Hello World '
s.strip()
s='#####Python#####'
s.strip('#')
s='Hello Python'
s.strip('Hln')
8. 6. s.startswith(prefix,start,end): This function has 3 arguments. The function return True is the s starts with specified
prefix, False otherwise.
Eg: s='hello world'
s.startswith('he')
s='hello world'
s.startswith('w',6)
s='hello world'
s.startswith('wo',6,10)
9. 7. s.count(s1,start,end): Takes 3 arguments. Returns number of occurrence of substring s1 in string s.
Eg: s='Hello how are you? How about you?'
s.count('h')
s.count('H')
s.count('how')
s.count('how',3,10)
10. Parsing Strings
Search for substring matching
Example is email-id of a person.
We want to extract the domain name [gmail/yahoo/outlook/rediffmail] in email
Identify the position of @ and identify the whitespace after @
Extract the substring between @ and whitespace
Eg: s='From bnmitguest@outlook.com Thursday March 12 2020'
atpos=s.find('@')
print('Position of @',atpos)
spacepos=s.find(' ',atpos)
print('Position of space after @ is',spacepos)
host=s[atpos+1:spacepos]
print(host)
11. f=open("C:/Users/Pooja B S/Documents/SDP on Python/abc.txt")
>>> print(f.read())
Hello Python Programming
Hello C Programming
Hello C++ Programming
Hello HTML Programming
Hello Perl Programming