STRING MANIPULATION
A string is a sequence of characters followed by ‘\0’.
\0 – null character
“Sbd international school”
‘sbd’
‘’’sbd’’’
“1234”
1234
Space= 32
String(st) s b d \0
Index(i) 0 1 2 3
What is the length of this string?
Traverse – passing though a string without imposing any condition
i=0
while(st*i+!=’\0’)
;;;;;
i+=1
at the exit point what would be the value of i ? 3
Learning Objective:
What is a string ?
Traversing a string ?
String operators…
String slices…
String Functions and methods
Strings can be indexed in both the directions.
L – R : positive indexing ( 0 to (length-1))
R – L : negative /backward indexing ( -1, -2, -3, ……)
02.01.2021
Traversing a string:
Traversing refers to iterating through the elements of a string, one
character at a time.
St = S c h o o l
0 1 2 3 4 5 ----- Positive indexing
-6 -5 -4 -3 -2 -1 ---- Backward indexing
Print st[2] = h
Print st[-4] = h
Program 1:
name=”superb”
for ch in name:
print(ch,’-‘, end =’ ‘)
the above code will print what?
s – u – p –e – r – b –
Program 2:
To print the string in reverse order. Do not create a reverse sting, just
display in reverse order.
St= “Python”
”nohtyP”
Code:
# to display the string in reverse order
# don't create the reverse string
string=input("Enter a string:")
print("The", string, "in reverse order is :")
length=len(string)
for i in range(-1,(-length - 1), -1):
print(string[i])
Note:
len( ) : is used to get the length of a string.
Syntax: len(string)
Output:
Enter a string:Python
The Python in reverse order is :
n
o
h
t
y
P
Program 3:
To read a string and display it in the form :
First character last character
Second character second last character
Third character third last character
::::::::::: :::::::::::::
Code:
# program to dipsaly first character and last character..
# second character and second last character and so on..
string=input("Enter a string:")
length=len(string)
a=0 # to display using positive index
for i in range(-1,(-length-1),-1): # I is used to display in negative index
print(string[a],"\t", string[i])
a+=1
Note:
“\t” : horizontal tab that generates 5 spaces.
Output:
Enter a string:Python
P n
y o
t h
h t
o y
n P
String Operators:
Strings are immutable i.e. they are not modifiable.
St1= “Python”
St2= “pYThon”
Basic operators : + and *
Membership operators : in and not in
‘+’ operator is also known and concatenation operator.
St1=”Python”
St2=”programming”
St1+St2 =Pythonprogramming
“123” + “456”
123456
‘2’+’4’ = ‘24’
‘a’+2 : error
2+4 = 6 ‘2’+’4’=’24’
‘*’ – string replication operator
Out of two operands one operand to be a number ,the operator to be a
string.
3*”happy”
“happyhappyhappy”
“abc” * 2 = “abcabc”
5 * ‘@’ = “@@@@@”
2*3 = 6
‘2’* = “222”
‘2’*’3’ : error
07.01.2021
Membership operators : in and not in.
These operators are applicable to all sequence type data.
in : Returns True if a character / substring exists in the given string ;
otherwise returns False.
not in: Returns True if a character / substring does not exists in the given
string ; otherwise returns False.
<string> in <string>
<string> not in <string>
Ex:
‘a’ in ‘agnita’ will give True
“nayak” in “Bisworanjan Nayak” will give False
“nayak” in “Bisworanjan nayak” will give True
>>>sub=”panda”
>>>string=”Mausami panda”
>>>sub1=’HELP’
>>>sub in string
True
>>>sub1 in string
False
>>>sub1 not in string
True
Program: Input an integer and check if it contains any 0 or not.
1093 =
“1093”
str : convert to string.
N is number N=1093
S=str(N) S=”1093”
Code:
N=input(“enter a number”)
S=str(N) # convert to a string
if ‘0’ in S:
print(“There’s a 0 in”, N)
else:
print(“No 0 in “,N)
Output:
enter a number : 1093
There’s a 0 in 1093
enter a number : 1293
No 0 in 1293
Comparison Operators:
<, <= , > , >=, ==, !=
=
==
A=5
>>>A
5
A==5
>>>A
False
“a”==”a” True
“ABC”==”abc” False
“abc”!=”Abc” True
‘a’<’A’ : False
‘ABC’>’AB’ True
‘abc’<=’ABCD’ False
‘abc’>’ABc’ : True
09.01.2021
A=10
>>>A
10
>>>str(A)
>>>A
‘10’
Determining Ordinal / Unicode Value of a Single character:
A
ord( ):
>>>ord(‘A’)
65
>>>ord(‘z’)
122
>>>ord(‘9’)
57
The ord( ) is opposite to chr( ).
print(‘=’ * 30)
=============================
print(‘=’*30)
print(‘\n’ * 9)
print(‘=’ *30)
=========================================
=========================================
Program: That asks a user for a username and a code. Ensure that the
user doesn’t user their username as part of their code.
Ex: uname=Sbdinternational
code=inter
Your code should not contain your username.
uname=input("enter user name:")
code=input("enter code:")
if uname in code:
print("Your code should not \
contain your user name.")
print("thank you")
Program: Write a program to print the following.
#
##
###
####
#####
string='#'
pattern=" " # empty string
for i in range(5):
pattern+=string ‘ ‘= ‘ ‘ +# #
print(pattern) #+# ##
12.01.2021
String Slices:
Part of a string containing some contiguous characters from the string.
name[a:b] { (b-1) }
word = a m a z i n g
0 1 2 3 4 5 6
-7 -6 -5 -4 -3 -2 -1
word*0:7+ = ‘amazing’
word*0:3+=’ama’
word*2:5+ =’azi’
word[-7:-3+= ‘amaz’
word[-5:-1+ = ‘azin’
word*:7+ =’amazing’
word*:5+=’amazi’
word[3:]=’zing’
word*5:+=’ng’
For any index n, s[:n] + s[n:] gives the original string.
>>>word[3:], word[:3]
‘zing’ ‘ama’
>>>word[:3]+word[3:]
‘amazing’
>>>word[:-7], word[-7:]
‘ ‘ ‘amazing’
>>>word[:-7]+word[-7:]
‘amazing’
Interesting factors:
1. We can give a third index (optional) in string slices.
>>>word[1:6:2] - here it will take every 2nd character starting from
index=1 till index<6
‘mzn’
>>>word[-7:-3:3]
‘az’
>>>word[: : -2] every 2nd character taken backwards
‘giaa’
>>>word[: : -1] every character taken backwards
‘gnizama’
2. S=”Hello”
print(S[5]) will report an error as 5 is out of the index.
print(S[4:8]) error
print(S[5 : 10]) will raise an error, but (when executed in shell) viz:
>>> s="hello"
>>> print(s[5:10])
‘ ‘
>>>
The blank line in between two prompts indicates an empty string.
Why?
The reason by default a slice from an string will return a string.
Since both the limits are out of bounds, it returns a string without
any characters that is ‘an empty string’.
Program:
To input a string and check if it is a palindrome string using a string
slice.
Liril madam Malayalam noon
#code
S=input(“enter a string”)
if (S == S[: : -1]):
print(S,’is palindrome’)
else:
print(S,’is not palindrome’)
String Functions:
1. len( )
Syntax:
len(<string>)
Purpose:
returns length of the given string (counts number of characters in
the string)
Examples:
>>>len(“hello”)
5
>>>len(‘school’)
6
2. capitalize( )
Syntax:
<string>.capitalize( )
Purpose:
Returns a copy of the string with its first character capitalized.
Example:
>>>’true’.capitalize( )
True
>>>’i love my India’.capitalize( )
I love my India
3. count( ) method
Syntax:
<string>.count(sub[ , start [, end ] ])
Purpose:
It returns the number of occurrences of the substring (sub) in string
(or string[start:end]).
Examples:
>>>’computerscience’.count(‘e’)
It counts the number of occurances of the substring ‘e’ in the main
string.
3
>>>’computerscience’.count(‘ce’)
1
>>>’computer’.count(‘c’,3,7)
0
4. find()
Syntax:
<string>.find(sub[ , start [, end ] ])
Purpose:
It returns the lowest index in the string where the substring (sub) is
found within the slice range of start and end.
Returns – 1 if sub in not found.
Example:
>>> st=‘ringa ringa roses’
>>>sub=’ringa’
>>>[Link](sub)
1
>>>st=’it goes as – ringa ringa roses’
>>>[Link](sub)
13
>>>[Link](sub,15,22)
-1
5. index( )
Syntax:
<string>.index(sub[ , start [, end ] ])
Purpose:
It returns the lowest index where the specified substring is found.
It the substring is not found then an exception , ValueError,is raised.
It works like find(), but find( ) returns -1 is the sub is not found.
BUT
index( ) raises an exception, if the sub is not found.
Example:
>>>st=’it goes as – ringa ringa roses’
>>>sub=’ringa’
>>>[Link](sub)
13
>>>[Link](sub,15,22)
ValueError : substring is not found
Q: Compare and contrast between index( ) and find( ) with respect to
string functions? (2)
6. isalnum( )
Syntax:
<string>.isalnum()
Purpose:
It returns True if the characters in the string are alphanumeric
(alphabets or numerics)and there is at least one character. False
otherwise.
Note: the space(‘ ‘) is not treated as alphanumeric.
Example:
>>>st1=”abc123”
>>>st2=”hello”
>>>st3=”123”
>>>st4=’ ‘
>>>[Link]( )
True
>>>[Link]()
True
>>>[Link]()
True
>>>[Link]()
False
Hint: To check if a character(ch) is a space or a special character,
you can use [Link]()!=True.
7. isalpha( )
Syntax: <string>.isalpha()
Purpose:
It returns True if all characters in the string are alphabets.
Example:
>>>st1=”abc123”
>>>st2=”hello”
>>>st3=”123”
>>>st4=’ ‘
>>>[Link]( )
False
>>>[Link]()
True
>>>[Link]()
False
>>>[Link]()
False
14.01.2021
8. isdigit( )
Syntax: <string>.isdigit()
Purpose:
It returns True if all characters in the string are digits.
Example:
>>>[Link]( )
False
>>>[Link]()
False
>>>[Link]()
True
>>>[Link]()
False
9. islower()
Syntax: <string>.islower()
Purpose:
It returns True if all cased characters in the string are in lower case.
Example:
>>>st1=’hello’
>>>[Link]()
True
>>>st2=’HeLlo’
>>>[Link]()
False
[Link]()
>>>st1=”HELLO”
>>>[Link]()
True
[Link]()
It returns True if there are only whitespace characters in the string.
<string>.isspace()
Exa:
>>>st1=” “ # stores 4 spaces
>>>[Link]()
True
>>>st2=”” # an empty string
>>>[Link]()
False
12. lower()
<string>.lower()
>>>st1=”HELLO”
>>>[Link]()
hello
13. upper()
<string>,upper()
>>>st1=’hello’
>>>[Link]()
HELLO
14. lstrip(),rstrip(),strip()
lstrip() : Returns a copy of the string with leading while spaces removed..
i.e. whitespaces from the leftmost end are removed.
<string>.lstrip()
Example:
>>>” Scie “.lstrip()
‘Scie ‘
rstrip() : trailing spaces
>>>” Scie “.rstrip()
‘ Scie’
strip( ): removes both leading and trailing spaces.
>>>” Scie “.strip()
Scie
15. startswith() , endswith()
startwith() : returns True if the string starts with the substring ‘sub’,
otherwise False.
<string>.startswith(<sub>) ‘
Ex: “abcd”.startswith(“cd”)
False
“abcd”.startswith(“ab”)
True
endswith():
>>>”abcd”.endswith(“cd”)
True
>>>”abcd”.endswith(“ab”)
False
16. title()
<string>.title()
It returns a title cased version of the string where all the words start with
uppercase characters.
>>>st=”today is the festival of makar sankranti”
>>>[Link]()
Today Is The Festival Of Makar Sankranti
17. istitle()
>>>”Computer Science”.istitle()
True
>>>”COMputer ScienCE”.istitle()
False
18. replace()
It returns a copy of the string with all occurrences of substring ‘old’
replaced by ’new’ string.
<string>.replace(old,new)
>>>”I work for you”.replace(‘work’,’care’)
I care for you
>>>”you and I work for you”.replace(‘you’,’U’)
U and I work for U
19. join( )
It joins a string or character after each member of the string iterator
i.e string based sequence.
(a) <string>,join(<stringiterable>)
>>>”*”.join(“Hello”)
H*e*l*l*o
>>>”@@@”.join(“TRIAL”)
T@@@R@@@I@@@A@@@L
(b)
>>>”$$”.join(*“trial”,”hello”+)
trail$$hello
>>>”##’.join((“trail”,”hello”,”new”))
trail##hello##new
>>>”##”.join((123,”hello”)
Error.
15.01.2021
20. split( )
Syntax: <string>.split(<str/char>)
Purpose:
It splits a <string> based on given< str or char>.
It returns a list containing split strings as members.
Case 1:
If you do not provide any argument to split, then by default it will split the
string considering whitespace as a separator.
Ex:
>>>”I love Python”.split()
[‘I’,’love’,’Python]
Case2:
If you provide any argument(str or char) to split, then the given string is
divided into parts considering the given (str or char) as separator and the
separator character is not included in the split string.
Ex:
>>>”I Love Python”.split(“o”)
[‘I L’,’ve Pyth’,’n’]
21. partition( )
Syntax: <string>.partition(<separator/string>)
Purpose:
It splits the string at the first occurance of separator, and returns a tuple
containing three items.
(a) The part before the separator
(b) The separator itself
(c) The part after the separator
Ex:
>>>txt=”I enjoy working in Python”
>>>x=[Link](“working”)
>>>print(x)
(‘I enjoy’,’working’,’in Python’)
>>> txt="I enjoy working in Python"
>>> x=[Link]("working")
>>> print(x)
('I enjoy ', 'working', ' in Python')
>>> txt="I enjoy working in Python working in shell"
>>> x=[Link]("working")
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
x=[Link]("working")
NameError: name 'text' is not defined
>>> x=[Link]("working")
>>> print(x)
('I enjoy ', 'working', ' in Python working in shell')
>>> "I Love Python".split()
['I', 'Love', 'Python']
>>> "I Love Python".split("o")
['I L', 've Pyth', 'n']
>>> x=[Link]("working")
>>> print(x)
['I enjoy ', ' in Python ', ' in shell']
>>>
[Link] is the difference between split() and partition() in Python.
Ans.
split() partition()
1 Will split the string at any Will only split the string at the first
occurrence of the given occurrence of the given argument.
argument
2 Return type: list Return type: tuple
3 The length of the list is equal Tuple of length =3, with the given
to the number of words, if separator as the middle value of the
split on whitespace tuple.
Program:
To read a line and print Number of upper case letters, small letters,
alphabets, digits, number of symbols.
Enter a line: Hello 123, Computer science, PYTHON