Lesson 5 Strings
Lesson 5 Strings
String Manipulation
Python does not support a character type. These are treated as strings of length
one.
Creating a string
Examples:
a="good morning"
>>>a
'good morning'
>>> print(a)
good morning
Error:
a='good"
Opening and closing quotes must be either single or double in both ends.
Empty string:
1
>>> print(str)
If a command is long, it can be shifted to the next line by typing ‘\’ but it shows
the result in the same line.
>>> print(a)
Here is a line split in 2 lines
If the output has to be displayed on the next line then the escape sequence \n can
be used.
We are Indians
and we love our country
Riya XI B
Multiline Strings:
>>> a='''This is
a multiline
string example'''
>>> print(a)
This is
a multiline
string example
>>> a="""This is
a multiline
string example"""
>>> print(a)
This is
a multiline
string example
Traversing a string:
Traversing means accessing all the elements of the string one after the other by
using subscript or index value. Each character in a string is located in different
slots. Each character has index value. Index starts from 0 and it must be an
integer. Individual elements of the string can be accessed by typing index value
inside square brackets.
Example
h e l l o w o r l d !
0 1 2 3 4 5 6 7 8 9 10 11
3
-12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
str=”Computer Science”
a="hello world!"
print(a[0])
print(a[4])
print(a[-6])
print(a[-5])
Output
h
o
w
o
We can’t use float or other data types for index as this will result in TypeError.
Trying to access a character out of index range will raise an Index error.
We can start the index either from left side or from right. Left index starts from
0 and right index starts from -1.
Str H e l l o w o r l d !
PI 0 1 2 3 4 5 6 7 8 9 10 11
PI – Positive Index
NI – Negative Index
str="Python"
for i in str:
print(i)
Output
P
y
4
t
h
o
n
Write a program to read a string and print it in reverse order. Display one
character per line. Do not create a reverse string , just display in reverse order.
etc…
For example ‘try’ should print as:
t y
r r
y t
Basic operators
+ Performs concatenation
* Performs replication
Concatenation of strings
print('Computer'+'Science')
ComputerScience
2+3
5
Invalid Example
'2'+3
Internally Python creates a new string in the memory by storing the individual
characters of the first string operand followed by the individual characters of
the second operand.
t e a
6
+
p o t
=
t e a P o t
Original strings are not modified as strings are immutable. New strings can be
created and existing strings cannot be modified.
To use * operator with strings ,you need two types of operands – a string and a
number.
The string operand tells the string to be replicated and the number operand tells
the number of times it is to be repeated.
Example
3*"Python"
'PythonPythonPython'
Invalid Example
'2'*'2'
TypeError: can't multiply sequence by non-int of type 'str'
Membership operators
not in operator – returns true if a character/substring does not exist in the given
string
7
Syntax
<substring> in <string>
Example
'h' in 'hello'
True
'H' in 'hello'
False
Note
Comparison operators
Examples
"a"=="a"
True
>>> "A"!="a"
True
>>> "abc"!="Abc"
True
8
Characters Ordinal
values
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
'abcd'>'abcD'
True
Python offers built in function ord() that takes a single character as input and
returns the corresponding ordinal Unicode value .
Syntax
ord(<single character>)
ord('A')
65
ord('\n')
10
chr(<int>)
chr(65)
‘A’
Note
9
Python compares two strings character by character according to their ASCII
values ,until it finds elements that differ. Subsequent elements are not
considered.
String Slicing
Syntax
Python will return a slice of the string by returning characters falling between
the starting position till end-1.
Examples
String A S A V E M O N E Y
Positive Index 0 1 2 3 4 5 6 7 8 9
>>>a="SAVE MONEY"
>>>a[1:3]
'AV'
>>> a[:3]
'SAV'
>>> a[3:]
'E MONEY'
>>> a[:]
'SAVE MONEY'
>>> a[-2:]
'EY'
>>> a[:-2]
'SAVE MON'
>>> print(a[:-2])
10
SAVE MON
>>> a[::2]
'SV OE'
>>> a="compute"
>>> print(a[3:],a[:3])
pute com
>>> print(a[:3]+a[3:])
compute
compute
>>> print(a[:-7]+a[-7:])
compute
>>> print(a[1:6:2])
opt
>>> print(a[-7:-3:3])
cp
>>> print(a[::2])
cmue
>>> print(a[::-1])
etupmoc
>>> print(a[-7:-3:3])
cp
>>> print(a[0:6])
comput
Write a program that prints the following pattern without using any nested
loops.
11
#
##
###
####
#####
str='#'
pattern=' '
for a in range(5):
pattern+=str
print(pattern)
Note
Index out of bounds causes error with strings but slicing a string outside the
bounds does not cause error.
Example
s="hello"
>>> s[5]
>>> print(s[4:8])
o
>>> print(s[5:10])
No output
Note
Syntax
<stringObject>.<method name>()
12
<sringObject> is a string only.
1. len()
Syntax:
len(str)
Usage:
Example:
str="Good Morning"
print(len(str))
12
19
2. capitalize()
Syntax:
str.capitalize()
Usage:
This method the exact copy of the string with the first letter in uppercase.
Example:
str="iam a student"
print(str.capitalize())
Iam a student
3. title()
13
Syntax:
str.title()
Usage:
This function returns the string with first letter of every word in the string
in uppercase and rest in lowercase.
Example:
Output
Thus, title() returns a version of the string where each word is title cased.
4. upper()
Syntax:
str.upper()
Usage:
Example:
str1="abc123"
str2="hello"
str3="HAI"
str4="12345"
str5=''
str6='$#@!'
str7="I am a TEACHER"
print(str1.upper())
print(str2.upper())
print(str3.upper())
print(str4.upper())
14
print(str5.upper())
print(str6.upper())
print(str7.upper())
ABC123
HELLO
HAI
12345
$#@!
I AM A TEACHER
5. lower()
Syntax:
str.lower()
Usage:
Example:
str1="abc123"
str2="hello"
str3="HAI"
str4="12345"
str5=''
str6='$#@!'
str7="I am a TEACHER"
print(str1.lower())
print(str2.lower())
print(str3.lower())
print(str4.lower())
print(str5.lower())
print(str6.lower())
print(str7.lower())
abc123
15
hello
hai
12345
$#@!
i am a teacher
6. count()
Syntax:
Usage:
This function returns number of times substring str occurs in the given
string. If we do not give start index and end index then searching starts
from index 0 and ends at length of the string.
[Stops the search with end-1]
Example:
Output
2
3
Output
Output
16
1
7. find()
Syntax:
str.find(sub[,start[,end]])
Usage:
This method returns the lowest index in the string where the substring sub
is found within the slice range of start and end. Returns -1 if substring is
not found. [Stops the search with end-1]
Example:
13
19
-1
19
17
print(str.find(sub,15,23))
-1
8. index()
Syntax:
str.index(sub[,start[,end]])
Usage
It returns the lowest index where the specified substring is found. If the
substring is not found then an exception, ValueError is raised. It works
like find(), but find() returns -1 if the substring is not found. But index()
function raises an exception, if substring is not found in the string.
[Stops the search with end-1]
Example
str="abracadabra"
print(str.index('ab'))
print(str.index('ab',6))
Output
0
7
Example
str="abracadabra"
print(str.index('ab',4,8))
str="abracadabra"
print(str.index('ab',4,9))
Note
18
Use index() and find() functions only when you want to know the index
position of the substring. For checking the presence of a substring, in
operator can be used.
9. isalnum()
Syntax:
str.isalnum()
Usage:
This method returns True if the characters in the string are alphanumeric
meaning alphabet letters (a-z) and numbers (0-9) and there is at least one
character, False otherwise.
Example:
str1="abc123"
str2="hello"
str3="12345"
str4=''
str5='$#@!'
str6='123@#$'
str7='123dfdf'
str8='123dfjdfj*&^%$'
print(str1.isalnum())
print(str2.isalnum())
print(str3.isalnum())
print(str4.isalnum())
print(str5.isalnum())
print(str6.isalnum())
print(str7.isalnum())
print(str8.isalnum())
True
True
True
19
False
False
False
True
False
10. islower()
Syntax:
str.islower()
Usage:
This method returns True if all the characters in the string are lower case
and there is at least one character, False otherwise.
Example:
str1="abc123"
str2="hello"
str3="HAI"
str4="12345"
str5=''
str6='$#@!'
str7="I am a TEACHER"
print(str1.islower())
print(str2.islower())
print(str3.islower())
print(str4.islower())
print(str5.islower())
print(str6.islower())
print(str7.islower())
True
True
False
False
False
False
False
11. isupper()
20
Syntax:
str.isupper()
Usage:
This method returns True if all the characters in the string are upper case
and there is at least one character, False otherwise.
Example:
str1="abc123"
str2="hello"
str3="HAI"
str4="12345"
str5=''
str6='$#@!'
str7="I am a TEACHER"
print(str1.isupper())
print(str2.isupper())
print(str3.isupper())
print(str4.isupper())
print(str5.isupper())
print(str6.isupper())
print(str7.isupper())
False
False
True
False
False
False
False
12. isspace()
Syntax:
str.isspace()
Usage:
This method returns True if there are only white space characters in the
string and there is at least one character, False otherwise.
21
Example:
True
False
False
False
13. isalpha()
Syntax:
str.isalpha()
Usage:
This method returns True if all the characters in the string are alphabetic
and there is at least one character, False otherwise.
Example:
str1="abc123"
str2="hello"
str3="12345"
str4=''
str5='$#@!'
str6='123@#$'
str7='123dfdf'
str8='123dfjdfj*&^%$'
print(str1.isalpha())
print(str2.isalpha())
print(str3.isalpha())
22
print(str4.isalpha())
print(str5.isalpha())
print(str6.isalpha())
print(str7.isalpha())
print(str8.isalpha())
False
True
False
False
False
False
False
False
14. isdigit()
Syntax:
str.isdigit()
Usage:
This method returns True if all the characters in the string are digits and
there is at least one character, False otherwise.
Example:
str1="abc123"
str2="hello"
str3="12345"
str4=''
str5='$#@!'
str6='123@#$'
str7='123dfdf'
str8='123dfjdfj*&^%$'
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
print(str4.isdigit())
print(str5.isdigit())
print(str6.isdigit())
print(str7.isdigit())
23
print(str8.isdigit())
False
False
True
False
False
False
False
False
15. split()
Syntax:
str.split(<string/character>)
Usage:
Splits a string str based on a given string or character and returns a list
containing split strings as members.
Example
24
If a string or a character is provided as an argument to split(), then
the given string is divided into parts considering the given string /
character as separator and the separator character is not included in
the split strings.
16. partition()
Syntax:
str.partition(separator/string)
Usage:
The partition method splits the string at the first occurrence of the
separator, and returns a tuple containing three items:
i) The part before the separator
ii) The separator itself
iii) The part after the separator.
Example:
Output
split() partition()
split() will split the string at partition() will only split the
any occurrence of the given string at the first occurrence of
argument the given argument
It returns a list containing the It returns a tuple containing
split substrings the split substrings
25
The length of the list is equal to It will always return a tuple of
the number of words, if split on length 3, with the given
whitespaces. separator as the middle value
of the tuple.
17. strip()
Syntax:
str.strip()
Usage:
This function returns the string after removing the spaces both on the left
and the right of the string.
Example:
Output:
18. lstrip()
Syntax:
str.lstrip([chars])
Usage:
This method returns a copy of the string with leading characters removed.
If used without argument it removes the leading white spaces. The
optional chars argument can be used to specify the set of characters to be
removed. The chars argument is not a prefix, rather all combinations of
its values (all possible substrings from the given string argument chars)
are stripped when they lead the string, until the left character of the string
mismatches.
Example:
26
>>> str=" hello"
>>> str.lstrip()
'hello'
str1="There"
print(str1.lstrip('the'))
There
str1="There"
print(str1.lstrip('The'))
re
str1="There"
print(str1.lstrip('Teh'))
re
str1="There"
print(str1.lstrip('he'))
There
str1="There"
print(str1.lstrip('heT'))
re
str1="There"
print(str1.lstrip('het'))
There
str1="There"
print(str1.lstrip('eTh'))
re
str1="There"
print(str1.lstrip('eT'))
27
here
str1="There"
print(str1.lstrip('e'))
There
str1="There"
print(str1.lstrip('Te'))
here
19. rstrip()
Syntax:
str.rstrip([chars])
Usage:
This method returns a copy of the string with trailing characters removed.
If used without argument it removes the trailing white spaces. The
optional chars argument can be used to specify the set of characters to be
removed. The chars argument is not a suffix, rather all combinations of its
values (all possible substrings from the given string argument chars) are
stripped, ,until the right character of the string mismatches.
Example:
'hello'
str1="There"
print(str1.rstrip('ere'))
Th
str1="There"
print(str1.rstrip('care'))
28
Th
str1="There"
print(str1.rstrip('her'))
str1="There"
print(str1.rstrip('herT'))
Empty string
str1="There"
print(str1.rstrip('hert'))
20. replace()
Syntax:
Usage:
Replaces a word or part of the string with another in the given string str.
Example:
Output:
I Love Programming
29
21. join()
Syntax:
str.join(string iterable)
Usage:
Joins a string or character after each member of the string iterator ie., a
string based sequence.
If the string based iterator is a string then the str is inserted after every
character of the string.
Example:
i) s="Hello"
print("*".join(s))
H*e*l*l*o
ii) print("&&&".join("Hello"))
H&&&e&&&l&&&l&&&o
iii) print("&&&".join(["Hello","Python"]))
Hello&&&Python
iv) print("&&&".join(["Hello","Python","Demo"]))
Hello&&&Python&&&Demo
30
v) print("&&&".join([123,"Python","Demo"]))
vi) print("&&&".join(("123","Python","Demo")))
123&&&Python&&&Demo
22. istitle()
Syntax:
str.istitle()
Usage:
This method does not take any arguments. It returns True if the string is
in title case, returns False if the string is not title cased or if it is an empty
string.
Example:
True
False
str="This Is @ Symbol"
print(str.istitle())
True
str="PYTHON"
31
print(str.istitle())
False
23. swapcase()
Syntax:
str.swapcase()
Usage:
This method does not take any arguments. It converts and returns all
uppercase characters into lowercase and vice versa of the given string.
Example:
str="PYTHON"
print(str.swapcase())
python
str="PyThOn"
print(str.swapcase())
pYtHoN
24. startswith(),endswith()
Syntax:
str.startswith()
Usage:
This method returns True if the string starts with the substring sub,
otherwise returns false.
32
Syntax:
str.endswith()
Usage:
This method returns True if the string ends with the substring sub,
otherwise returns false.
Example:
print("abcd".startswith("cd"))
False
print("abcd".startswith("ab"))
True
print("abcd".endswith("b"))
False
print("abcd".endswith("cd"))
True
Write a program to read a line and display all the words starting with m.
Output
my
mobile
Write a program that reads a line and a substring . It should then display
the number of occurrences of the given substring in the line.
33
line=input("Enter a line:")
sub=input("Enter a substring:")
length=len(line)
lensub=len(sub)
start=count=0
end=length
while True:
pos=line.find(sub,start,end)
if pos != -1:
count+=1
start=pos+lensub
else:
break
if start >=length:
break
print("No of occurrences of substring:",count)
Programs
a=input("Enter a line:")
uc=lc=dig=al=0
for i in a:
if i.isupper():
uc+=1
elif i.islower():
lc+=1
elif i.isdigit():
dig+=1
if i.isalpha():
al+=1
34
print("No of UC letters:",uc)
print("No of LC letters:",lc)
print("No of digits:",dig)
print("No of alphabets:",al)
word='pineapple'
count=0
for letter in word:
if letter in('a','e','i','o','u'):
count+=1
print(count)
35
4) Write a program that reads a string and prints a string that capitalizes
every other letter in the string.
s1=input("Enter a string")
le=len(s1)
print("Original string is:")
s2=""
for a in range(0,le):
if a%2==0:
s2+=s1[a]
else:
s2+=s1[a].upper()
print(s2)
Input:school
Output: sChOoL
5. Write a program that reads a string and counts the number of words in the
string.
s1=input("Enter a string")
n=len(s1)
c=0
for i in range(n):
if s1[i]==' ':
c+=1
print(c)
OR
s1=input("Enter a string")
n=len(s1)
c=0
for i in range(n):
if s1[i].isspace():
c+=1
print(c)
36
6. Write a program to remove the vowels from the string.
s1=input("Enter a string")
s2=" "
n=len(s1)
for i in range(n):
if s1[i] not in "aeiouAEIOU":
s2+=s1[i]
print("Orignal string is:",s1)
print("New string is:",s2)
s1="INSTITUTE"
s2=" "
n=len(s1)
for i in range(n):
if s1[i] not in 'T' :
s2+=s1[i]
print("Orignal string is:",s1)
print("New string is:",s2)
Output:
Orignal string is: INSTITUTE
New string is: INSIUE
8. Write a program that inputs a main string and then creates an encrypted
string by embedding a short symbol based string after each character. The
program should be able to produce the decrypted string from encrypted
string.
def encrypt(sttr,enkey):
return enkey.join(sttr)
37
def decrypt(sttr,enkey):
return sttr.split(enkey)
#_main_
mainstring=input("Enter main string")
encryptstr=input("Enter encryption key")
enstr=encrypt(mainstring,encryptstr)
delst=decrypt(enstr,encryptstr)
destr="".join(delst)
print("The encrypted string is",enstr)
print("The string after decryption is",destr)
Output
38