</CHAPTER - 2>
PYTHON
REVISION
TOUR-II
STRINGS
</STRINGS>
Strings are data types in Python stored as individual
characters in contiguous locations, with two - way
index for each location and enclosed in double or single
quotes.
</ACCESSING DATA IN STRINGS>
</STRINGS>
Length of a string can be found with help of len(). Len
function accepts only a string object as argument and
gives the length of the particular string.
a = "apple" a = "apple\ a = """Mark
ball" john"""
len(a)-> 5 len(a) -> 9 len(a) —> 9
02
TRAVERSING A STRING
</TRAVERSING A STRING>
If you want to loop through the values
of a string directly you can use the
previous slide methodology.
What method you can follow to access
the elements of a string using its
index value ?
If you want to to loop through a string from
left to right the range can be given as below
"John"
a = "John"
for i in range(len(a)):
print(a[i],end=" ")
If you want to to loop through a string from
right to left (reverse) the range can be
given as below
"Mark"
a = "Mark"
for i in range(-1,-len(a)-1,-1):
print(a[i],end=" ")
Write a program to accept a string
from the user and print the string in
the given reversed format below
Enter a String : apple
e**l**p**p**a
03
STRING OPERATIONS
</STRING OPERATORS>
String Operators tools which are used to
manipulate strings and perform operations on
them.
</STRING REPLICATION>--→* Repeating time
“*” Is used as an arithmetic multiplication
operator when used with numbers but used as
replication or cloning operator when used with
strings.
</STRING REPLICATION>--→* Repeating time
“John” * 3 —> JohnJohnJohn
3 * “John” —> JohnJohnJohn
-2 * “John” -> Blank Output screen
2.5 * “John” -> Type Error
“3” * “5” —> Type Error
</STRING MEMBERSHIP> --→ in & not in
in - Returns True if a character or a substring
exists in a given string; False Otherwise.
not in - Returns True if a character or a
substring doesn’t exists in a given string;
False Otherwise.
</STRING MEMBERSHIP> --→ in & not in
print("Jap" in "japan") -> False
print(“a” in “heya”) -> True
print(“jap” in “japan”) -> True
print(“paj” in “japan”) -> False
</STRING MEMBERSHIP> --→ in & not in
print(“123” not in “hello”) -> True
print(“123” not in “12345”) -> False
</STRING CONCATENATION> ----→ + Joining
“+” Is used as an arithmetic addition operator
when used with numbers but used as joining
operator when used with strings.
</STRING CONCATENATION> ----→ + Joining
</STRING COMPARISON>→ >,==,<,!= Compare
Pythons standard comparison operators
applies to strings also.
</STRING COMPARISON>→ >,==,<,!= Compare
“a” == “a” will result - True
“a” == “a” will result - True
“a” != “abc” will result - True
</STRING COMPARISON>→ >,==,<,!= Compare
“ABC” == “abc” - will return False
“abc” != “Abc” - will return True
</STRING COMPARISON>→ >,==,<,!= Compare
a = “True”
b = True
print(a == b) —> False
</STRING COMPARISON>→ >,==,<,!= Compare
For equality operators comparison can
be done easily because while comparing
the strings each character of string
will be checked whether it is matching
or not along with case.
</STRING COMPARISON>→ >,==,<,!= Compare
But for > or < you should know the
ordinal values to compare the strings
</STRING COMPARISON>→ >,==,<,!= Compare
‘a’ < ‘A’ -> False
‘ABC’ > ‘AB’ - True
‘abc’ <= ‘ABCD’ - False
‘abcd’ > ‘abcD’ - > True
</STRING COMPARISON>→ >,==,<,!= Compare
Python offers built in function like ord() and
chr() to determine ordinal values of a single
character
</STRING COMPARISON>→ >,==,<,!= Compare
ord() will accept only one single string
character and return the ordinal value.
>>>ord(‘A’)
65
</STRING COMPARISON>→ >,==,<,!= Compare
chr() is opposite of ordinal where the character
corresponding character of the ordinal value
will be displayed.
</STRING COMPARISON>→ >,==,<,!= Compare
>>>chr(65)
A
04
STRING SLICING
</STRING SLICING>
In english slice word means - “a part of”. In
the same way, in Python slicing means refers
to a part of the string where strings are sliced
using a specific range.
</STRING SLICING>
For a String name , if we give name[n : m]
Where n and m are integers for the range of
indexes to be sliced.
</STRING SLICING>
For a String name , if we give name[n : m]
Python will return a slice of the string by
returning characters falling between indices n
and m - Starting at n and ending at m-1.
</STRING SLICING>
For a String name , if we give name[n : m]
Python will return a slice of the string by
returning characters falling between indices n
and m - Starting at n and ending at m-1.
</STRING SLICING>
For a String name , if we give name[n : m]
n = lower limit and m = upper limit
</STRING SLICING>
For a String name , if we give name[n : m]
name
</STRING SLICING>
String Slicing Format :
stringName[begin Index:last Index]
</STRING SLICING>
name[0:6]
name
Python
</STRING SLICING>
name[0:3]
name
Pyt
</STRING SLICING>
name[2:5]
name
tho
</STRING SLICING>
name[-6:-3]
name
Pyt
</STRING SLICING>
name[-5:-1]
name
ytho
</STRING SLICING>
String Slicing Format :
stringName[begin Index:last Index]
</STRING SLICING>
stringName[begin Index:last Index]
If begin index not given default it will be
considered as 0
</STRING SLICING>
stringName[begin Index:last Index]
If last index not given default it will be considered
as length of string
</STRING SLICING>
name[:6]
name
Python
</STRING SLICING>
name[:4]
name
Pyth
</STRING SLICING>
name[2:]
name
thon
</STRING SLICING>
For any index n , s[:n] + s[n:] will give you the
original string
name = "Python"
</STRING SLICING> print(name[3:],name[:3])
print(name[:3]+name[3:])
name
O/P:
hon Pyt
Python
name = "Python"
</STRING SLICING> print(name[:-6])
print(name[-6:])
print(name[:-6]+name[-6:])
name
O/P:
Python
Python
</STRING SLICING>
name[1:6:2]
name
yhn
It will take every second
Character from starting
To the index<6
</STRING SLICING>
name[-6:-2:2]
name
Pt
It will take every third
Character from starting
To the index<-2
</STRING SLICING>
name[::-2]
name
nhy
Every 2nd character taken
Backwards from last
</STRING SLICING>
name[::-1]
name
nohtyP
Every character taken
Backwards from last
</STRING SLICING>
name[::-5]
name
nP
Every character taken
Backwards from last
Write a program that reads two times in military format (0900, 1730)
and prints the number of hours and minutes between the two times.
A sample run is being given below :
Please enter the first time : 0900
Please enter the second time : 1730
8 hours 30 minutes
05
STRING FUNCTIONS AND METHODS
</STRING FUNCTIONS AND METHODS>
Python offers many built in functions and methods for String
manipulation. You have already worked with one such method called
len() in earlier chapters.
In this chapter we are going to work with few more built in functions
using string objects.
</STRING FUNCTIONS AND METHODS>
str = "John"
for char in reversed(str):
print(char,end="")
</len() Function>
len() returns the length of the argument string. Its a standard library
function
Syntax - len(<string name>)
Examples - >>> name = “Maria”
>>>len(name)
5
</capitalize() method>
Returns the copy of the string with its first character capitalized.
Basically will convert to sentence case.
Syntax - <string>.capitalize()
Examples - >>> “i love india’.capitalize()
I love india
</count() method>
Return the number of occurrences of the substring sub in whole string.
Syntax - <string>.count(substring)
Examples - >>> print("abracadabra".count("ab"))
2
</count() method>
Return the number of occurrences of the substring sub in whole string.
Syntax - <string>.count(substr,start,end)
Examples - >>> print("abracadabra".count("ab",4,8))
0
</count() method>
Return the number of occurrences of the substring sub in whole string.
Syntax - <string>.count(substr,start,end)
Examples - >>> print("abracadabra".count("ab",6))
1
</find() method>
Returns lowest index in string where the substring is found with in the
slice range of start and end. Returns -1 if substring not found.
Syntax - <string>.find(substr,start,end)
Examples - >>>str = “It goes as - ringa ringa roses”
>>>sub = “ringa”
>>>str.find(sub)
13
</find() method>
Returns lowest index in string where the substring is found with in the
slice range of start and end. Returns -1 if substring not found.
Examples - >>>str = “It goes as - ringa ringa roses”
>>>sub = “ringa”
>>>str.find(sub,15,22)
-1
</find() method>
Returns lowest index in string where the substring is found with in the
slice range of start and end. Returns -1 if substring not found.
Examples - >>>str = “It goes as - ringa ringa roses”
>>>sub = “ringa”
>>>str.find(sub,15,25)
19
</index() method>
Returns lowest index in string where the substring is found with in the
slice range of start and end. Returns exception if substring is not found
Syntax - <string>.index(substr,start,end)
</index() method>
When substring is not found with find method it returns -1.
Syntax - <string>.index(substr,start,end)
>>> “abracadabra”.index(“ab”)
0
</index() method>
When substring is not found with find method it returns -1.
Syntax - <string>.index(substr,start,end)
>>> “abracadabra”.index(“ab”,6)
7
</index() method>
When substring is not found with find method it returns -1.
Syntax - <string>.index(substr,start,end)
>>> “abracadabra”.index(“ab”,4,8)
</isalnum() method>
Returns true if the characters in string alphabets or numbers or
combination of both
print(“abc”.isalnum()) - > True
print(“123”.isalnum()) - > True
print(“abc123”.isalnum()) - > True
print("ABC123".isalnum()) -> True
print(“abc ”.isalnum()) - > False
print(“abc@123”.isalnum()) - > False
</isalpha() method>
Returns true if the characters in string are only alphabets
print(“abc”.isalpha()) - > True
print(“123”.isalpha()) - > False
print(“abc@123”.isalpha()) - > False
</isdigit() method>
Returns true if the characters in string are only digits
print(“abc”.isdigit()) - > False
print(“123”.isdigit()) - > True
print(“abc@123”.isdigit()) - > False
</islower() method>
Returns true if the alphabets in string are only lowercase
print("123hello".islower()) -> True
print("@hello".islower()) -> True
print("123Hello".islower()) -> False
print("123".islower()) -> False
</isupper() method>
Returns true if the alphabets in string are only uppercase
print("123Hello".islower()) -> False
print("@HELLO".islower()) -> True
</isspace() method>
Returns true if the string has only whitespace characters.
str1 = ""
str2 = " "
str3 = " hell o"
print(str1.isspace()) - > False
print(str2.isspace()) -> True
print(str3.isspace()) -> False
</lower() method>
Returns copy of string converted to lowercase
print("HELLO123@#".lower()) - > hello123@#
print("hello123@#".upper().islower()) -> False
print("hello123@#".upper().lower()) -> hello123@#
</upper() method>
Returns copy of string converted to uppercase
print("hello123@#".upper()) -> HELLO123@#
</upper() method>
Returns copy of string converted to uppercase
print("hello123@#".upper()) -> HELLO123@#
</lstrip() method>
Returns copy of string with leading white spaces removed
print(" Sipo ".lstrip())
O/P -
Sipo
</swapcase() method>
Swaps all the current case in a string with opposite case :
a = "Apple"
print(a.swapcase())
O/P - aPPLE
</rstrip() method>
Returns copy of string with trailing white spaces removed
print(" Sipo ".rstrip())
O/P -
Sipo
</strip() method>
Returns copy of string with trailing and leading white spaces removed
print(" Sipo ".strip())
O/P -
Sipo
</startswith() and endswith() method>
startswith() - Returns True if the string starts with substring or False
endswith() - Returns True if the string ends with substring or False
>>> “abcd”.startswith(“cd”) >>> “abcd”.startswith(“ab”)
False True
>>> “abcd”.endswith(“b”) >>> “abcd”.endswith(“cd”)
False True
</title()>
Returns a title cased version of the string where all words start with
uppercase characters and all remaining letters in lowercase.
>>> “the sipo app”.title()
“The Sipo App”
>>> “COMPUTER SCIENCE”.title()
“Computer Science”
</istitle()>
Returns true if a string has a title cased version.
>>> “The Sipo App”.istitle()
True
>>> “COMPUTER SCIENCE”.istitle()
False
</replace() method>
Returns a copy of string with all occurrences of substring (old)
replaced by (new) string
Syntax - <string>.replace(old,new)
>>> “abracadabra”.replace( “ab” , “sp” )
“spracadspra”
>>> “I work for you”.replace( “work” , “care” )
“I care for you”
</join() method>
Joins a string or character after each member of the string iterator , a
string based sequence.
Syntax - <string>.join(string iterable)
>>> print("@".join("Hello World"))
H@e@l@l@o@ @W@o@r@l@d
>>>print("$$".join(("trial","hello","123")))
trial$$hello$$123
</join() method>
Joins a string or character after each member of the string iterator , a
string based sequence.
Syntax - <string>.join(string iterable)
>>> print("###".join(["trial","hello",12]))
ERROR!
Traceback (most recent call last):
File "<main.py>", line 1, in <module>
TypeError:sequence item 2:expected str instance,int found
</split() method>
It splits a string based on given string and returns a list containing
Split strings as members.
Syntax - <string>.split(string/char)
print("I Love Python".split())
</split() method>
It splits a string based on given string and returns a list containing
Split strings as members.
Syntax - <string>.split(string/char)
print("I Love Python".split("o"))
</split() method>
When the specified string is not found the whole string is returned as a
single element list Syntax - <string>.split(string/char)
print("I Love Python".split(" "))
</partition() method>
partition () method splits the string at first occurrence of separator and
returns a tuple containing three items
1. Part before separator Syntax - <string>.partition(<seperator>)
2. Seperator itself
3. Part after Seperator
</partition() method>
partition () method splits the string at first occurrence of separator and
returns a tuple containing three items
</Difference b/w split and partition method>
</Similarity b/w split and partition method>
Important - Empty separator must not be
given for both split and partition method.
print("I Love Python".partition(“”))
print("I Love Python".split(“”))