Unit-2 ch-9 Strings
Unit-2 ch-9 Strings
1|Page
Empty string:
str=“ “
If string is long then it can be shifted to the next line by typing ‘\’ but it shows
the output in the same line
Str=“ my school is \
the air force school “
This displays output in the same line. (demonstrated on next slide)
2|Page
Traversing a string
➢ Every character in a string is associated with index value 0 to n-1 where ‘n’ is the length of
string
➢ Python indexes the strings in 2 ways :
❑ Positive index (0 to n-1) from left to right
❑ Negative index (-1 to –n) from right to left
String Operators
1. String Operators : + and *
+ means “concatenate” joins the two strings one after the other
* means “replicate “ creates new strings, concatenating multiple copies of the same
string .
Example
Str1=“Hello”
Str2=“World”
print(Str1+Str2) # displays HelloWorld
print( Str1*2) # display HelloHello
3|Page
2. String Membership Operators : in and not in
in : Evaluates to true if it finds a variable in the specified sequence and false
otherwise.
not in : Evaluates to true if it does not finds a variable in the specified sequence and
false otherwise.
Example :
‘H’ in ‘PYTHON’ gives True
‘S’ in ‘PYTHON’ give False
‘H’ not in ‘PYTHON’ gives False
‘S’ not in ‘PYTHON’ gives True
4|Page
Immutable nature of strings
Strings in python are immutable which means we cannot make changes in an existing string
As string is immutable, we cannot change any character of string.
Str[3]=‘P’ gives error
5|Page
String Methods
1. len() This gives length of string( number of characters)
Example :
str=“computer”
print(len(str)) gives 8
2. capitalize() This will display string in Sentence case. First character of the string will be in
capital letter
Example :
str=“computer”
print(str.capitalize()) Computer
3. split() Break up a string at the specified separator and returns a list of substring.
str.split(separator, maxsplit)
separator (optional) is a delimiter
maxsplit(optional) is maximum number of splits
Example :
str = ‘this is a python class’
x = str.split()
print(x) #prints [ ‘this’ , ‘is’ , ‘a’ , ‘python’ , ‘class’ ]
6|Page
4. replace() this replace all the occurrence of old substring/string by a new substring/string if
found
Example :
str=“ India is my country”
print(str.replace(“my”, “our”)) now it displays India is our country
5. isalpha() returns True if string contains only letters otherwise returns False
Example :
str=“ India is my country”
str.isalpha() returns True
7|Page
6. isdigit() or isnumeric() returns True if string contains only digits otherwise returns False
Example :
str = ‘abc@123’
str2 = ‘123’
str.isdigit() returns False
str2.isdigit() returns True
8. istitle() Returns True if string is in title case otherwise returns False ( First character of
each word should be in capital)
Example :
str=“The Air Force School”
str.istitle() gives True
8|Page
9. isalnum() It checks whether all characters are only alphabets or digits or not. It returns
accordingly
Example :
str=“abc”
str1 = “@xyz”
str.isalnum() returns True
str1.isalnum() returns False
11. islower() Returns True if all letters of a string are in lower case otherwise returns False
Example :
str = “Tafs”
str.islower() returns False
9|Page
12. upper() converts string into uppercase letters
Example :
str = “Tafs”
str.upper() returns TAFS
13. isupper() Returns True if all letters of a string are in upper case otherwise returns False
Example :
str = “Tafs”
str.isupper() returns False
14. lstrip() or lstrip(char) Returns the string after removing the leading space or after removing
specific characters from left side
Example :
str=“ computer”
str1=“computer science”
str.lstrip() gives computer
str1.lstrip(‘co’) gives mputer science
15. rstrip() or rstrip(char) Returns the string after removing the leading space or after removing
specific characters from left side
Example :
str=“computer ”
str1=“computer scienceee”
str.rstrip() gives computer
str1.rstrip(‘ee’) gives computer science
10 | P a g e
16. join()
Returns a string in which the string elements have been joined
by a string separator
Example :
str1=‘12345’
s=‘-’
s.join(str) gives 1-2-3-4-5
17. swapcase() converts the cases of character in a string (lower to upper and vice versa)
Example :
str=‘PyTHoN’
str.swapcase() gives pYthOn
11 | P a g e
18. partition(separator) split the string by given string(separator). It gives a tuple.
Example :
str1=‘[email protected]’
str2=str1.partition(‘@’)
print(str2) gives ( ‘xyz’, ‘@’, ‘gmail.com’)
str3=str1.partition(‘ ‘)
print(str3) gives (‘[email protected]’, ’ ‘, ’ ‘)
12 | P a g e
20. ord() this function returns the equivalent ASCII value of a character.
ASCII values are assigned to each character ranges from 0 to 255
A=65, Z=90 a=97 z=122 0(zero)=48 9=57 etc
Example :
ch=‘b’
print( ord(ch)) gives 98
21. chr() this function returns the equivalent character for given ASCII value
Example :
print( chr(97)) gives ‘a’
13 | P a g e
22. find() The method find() determines if string str occurs in string, or in a substring of string if
starting index beg and ending index end are given.
str.find(str, beg,end)
Parameters
str -- This specifies the string to be searched.
beg -- This is the starting index, by default its 0.
end -- This is the ending index, by default its equal to the length of the string.
This method returns index if found and -1 otherwise.
Example :
str1 = "this is string example....wow!!!"
str2 = "exam"
print (str1.find(str2)) returns 15
print (str1.find(str2, 10)) returns 15
print (str1.find(str2, 40)) returns -1
23. rfind() The method is same as find() but searches from end.
str.rfind(str1, beg, end)
Example :
str1 = "this is string example"
str2 = "exam"
print (str1.rfind(str2)) 16
14 | P a g e
24. center() Returns a string with the original string centered to a total of width columns and filled
with fillchar in columns that do not have characters.
25. endswith() Checks if string ends with any substring(given). Returns True if so otherwise False.
You can set beginning index and end index also.
str.endswith(str1, beg, end)
Example :
str=“ The air force school”
str1 = “ol"
print (str.endswith(str1)) gives True
15 | P a g e
27. index() Same as find but raises error if substring not found.
Example :
str=“ He is my best friend”
print(str.index(“mine’)) raises an error
print(str.index(“be”)) gives 9
16 | P a g e
31. zfill() returns string left padded with zeros to a total of specified width.
Example :
str=“python”
print(str.zfill(10)) gives 0000python
32. max() Returns the highest alphabetical character( having highest ASCII value).
Example :
str=“best friend”
print(max(str)) gives ‘t’
33. min() Returns the lowest alphabetical character( having lowest ASCII value).
Example :
str=“python”
print( min(str)) gives ‘h’
17 | P a g e
String Constants:
Many modules in python library provide both functions and constants for dealing with various
elements of the program.
The string module provides various constants that are useful for various purposes.
We need to import string module before using any of the constants of this module with the
following statement:
import string
18 | P a g e
PROGRAMS
19 | P a g e
20 | P a g e
21 | P a g e
22 | P a g e
23 | P a g e
24 | P a g e
25 | P a g e