Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

Lesson 5 Strings

Uploaded by

mailjayane
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Lesson 5 Strings

Uploaded by

mailjayane
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Lesson 5

String Manipulation

What is a string in Python?

A consecutive sequence of characters which are enclosed or surrounded by


single or double quotes is known as a string. This sequence of character may
include a letter , a number , special character or a back slash. Strings are
immutable. That is every time you perform something on a string that changes it
, Python will internally create a new string rather than modifying an old string
in place.

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'

>>> 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:

>>> str=' '


>>> print(str)

>>> str=" "

1
>>> print(str)

Nothing will be printed

To print double quotes and single quotes use backslash(/)

>>> a="Write article on \"AI\" briefly"


>>> print(a)

Write article on "AI" briefly


>>> a
'Write article on "AI" briefly'

a="This is Meera\'s pen"


>>> print(a)
This is Meera's pen

If a command is long, it can be shifted to the next line by typing ‘\’ but it shows
the result in the same line.

>>> a="Here is a line \


split in 2 lines"

>>> 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.

>>> a="We are Indians \n and we love our country"


>>> print(a)

We are Indians
and we love our country

We can also use escape sequence (\t) to tabulate the output:

>>> a1="Name\t Class \t Section"


>>> print(a1)
2
Name Class Section

>>> a2="Riya \t XI \t B"


>>> print(a2)

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

NI -12 -11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

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.

str=input("Enter any string")


print("The",str,"in reverse order is")
length=len(str)
for i in range(-1,-length-1,-1):
print(str[i])

Enter any string python


The python in reverse order is
n
o
h
t
y
p

Write a program to read a string and display it in the form:

First character last character


Second character second last character

etc…
For example ‘try’ should print as:
t y
r r
y t

str=input("Enter any string")


length=len(str)
a=0
for i in range(-1,-length-1,-1):
print(str[i],'\t',str[a])
5
a+=1

Enter any string python


n p
o y
h t
t h
y o
p n

Special string operators

To manipulate the strings the basic operators + and * , membership operators in


and not in and comparison operators(all relational operators) are used.

Basic operators

The basic string operators are + and * .

+ Performs concatenation
* Performs replication

Concatenation of strings

Concatenation refers to creating a new string by adding two strings. To use +


operator ,data types should be the same. We cannot add str and int objects.

print('Computer'+'Science')
ComputerScience

2+3
5
Invalid Example

'2'+3

TypeError: must be str, not int

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.

String replication operator

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

Python offers two membership operators for checking whether a particular


character exists in the given string or not.

in operator – returns true if a character/substring exists in the given string

not in operator – returns true if a character/substring does not exist in the given
string

Both the operands should be of string type.

7
Syntax

<substring> in <string>

<substring> not in <string>

Example

'h' in 'hello'
True

'H' in 'hello'
False

'hel' not in 'hello'


False

Note

To use membership operators in strings both the operands should be of string


type.

Comparison operators

All relational operators are called comparison operators(>,<,>=,<=,==,!=) .


They can be used with strings. The comparison used by these operators are
based on the standard character by character comparison rules for Unicode.
(ASCII and Unicode values are the same for most characters)

Examples

"a"=="a"
True

>>> "A"!="a"
True

>>> "abc"!="Abc"
True

Common characters and their Ordinal values

8
Characters Ordinal
values

‘0’ to ‘9’ 48 to 57

‘A’ to ‘Z’ 65 to 90

‘a’ to ‘z’ 97 to 122

'a' < 'A'


False

'abcd'>'abcD'
True

Determining the Ordinal / Unicode value of a single character

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

( Escape sequences are considered as a single character only )


The opposite of ord() function is chr() function
chr() takes the ordinal value of a character in integer form and returns the
equivalent character corresponding to it.
Syntax

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

Slicing is used to retrieve a subset of values . A slice of a string is nothing but a


substring. This extracted substring is called as a slice.

Syntax

String_name[start:end] end is excluded

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

Negative Index -10 -9 -8 -7 -6 -5 -4 -3 -2 -1

>>>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'

This will print alternate characters from the string

>>> a="compute"

>>> print(a[3:],a[:3])
pute com

>>> print(a[:3]+a[3:])
compute

>>> print(a[:-7],a[-7:]) # a[:-7] refers to a[:-8] which is an invalid index .

Hence no output for a[:-7]

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]

IndexError: string index out of range

>>> print(s[4:8])
o
>>> print(s[5:10])

No output

Note

Strings are immutable . Once created strings cannot be changed.

String methods and built-in functions:

Python provides several built in functions associated with strings. These


functions allow us to easily modify and manipulate strings.

Syntax

<stringObject>.<method name>()

12
<sringObject> is a string only.
1. len()

Syntax:

len(str)

Usage:

This method returns the length of the string

Example:

str="Good Morning"
print(len(str))

12

str="This is Meera\'s pen"


print(len(str))

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:

str="hello ITS all about STRINGS!!"


print(str.title())

Output

Hello Its All About Strings!!

Thus, title() returns a version of the string where each word is title cased.

4. upper()

Syntax:

str.upper()

Usage:

This method returns a copy of the string converted to upper case.

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:

This method returns a copy of the string converted to lower case.

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:

str.count(substring, start, end)

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:

str="Hello World, Hello Hello"


print(str.count('Hello',12,25))
print(str.count('Hello'))

Output

2
3

str="Hello World, Hello Hello"


print(str.count('Hello',12,24))

Output

str="Hello World, Hello Hello"


print(str.count('Hello',12,23))

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:

str="it goes as - ringa ringa roses"


sub='ringa'
print(str.find(sub))

13

str="it goes as - ringa ringa roses"


sub='ringa'
print(str.find(sub,15,25))

19

str="it goes as - ringa ringa roses"


sub='ringa'
print(str.find(sub,15,22))

-1

str="it goes as - ringa ringa roses"


sub='ringa'
print(str.find(sub,15,24))

19

str="it goes as - ringa ringa roses"


sub='ringa'

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))

ValueError: substring not found

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 of characters that are not alphanumeric: (space) ! # % & ? etc.

If special characters are there it will return false.

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:

str1=" " #stores 3 spaces


str2="" #stores empty string
str3=''
print(str1.isspace())
print(str2.isspace())
print(str3.isspace())

True
False
False

str1="The School "


print(str1.isspace())

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

i) str="I Love Python"


print(str.split())

['I', 'Love', 'Python']

ii) str="I Love Python"


print(str.split(" "))

['I', 'Love', 'Python']


If no argument is provided to split then by default it will split the
given string considering white space as the separator.

iii) str="I Love Python"


print(str.split("o"))

['I L', 've Pyth', 'n']

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:

str="I enjoy working in Python"


print(str.partition('working'))

Output

('I enjoy ', 'working', ' in Python')

Difference between partition() and split()

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:

str=" Hello ITS all about STRINGS!! "


print(str.strip())

Output:

Hello ITS all about STRINGS!!

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:

>>> str="hello "


>>> str.rstrip()

'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:

str.replace(<word to be replaced>,<replace word>)

Usage:

Replaces a word or part of the string with another in the given string str.

Example:

str="I Love Python"


print(str.replace("Python","Programming"))

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

If the string based iterator is a list or a tuple of strings then the


given string/character is joined with each member of the list or
tuple. But the list or tuple must have all members as strings , else
Python will raise an exception.

iii) print("&&&".join(["Hello","Python"]))

Hello&&&Python

iv) print("&&&".join(["Hello","Python","Demo"]))

Hello&&&Python&&&Demo

30
v) print("&&&".join([123,"Python","Demo"]))

TypeError: sequence item 0: expected str instance, int found

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:

str="All Learn Python"


print(str.istitle())

True

str="All learn Python"


print(str.istitle())

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.

St= "where is my mobile"


for i in St.split():
if i.startswith("m"):
print(i)

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)

Enter a line:jingle bells jingle bells jingle all the way


Enter a substring:jingle
No of occurrences of substring: 3

Programs

1) Write a program that reads a line and prints the number of UC ,


LC,Alphabets and digits in it.

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)

Enter a line:Hello 123, ZIPPY zippy Zap


No of UC letters: 7
No of LC letters: 11
No of digits: 3
No of alphabets: 18

2) Write a program to count the number of vowels in the string ‘pineapple’.

word='pineapple'
count=0
for letter in word:
if letter in('a','e','i','o','u'):
count+=1
print(count)

3) Write a program to check if the given string is a palindrome or not.

s=input("Enter the string")


l=len(s)
p=l-1
index=0
while index<p:
if(s[index]==s[p]):
index+=1
p-=1
else:
print("String is not a palindrome")
break
else:
print("String is a palindrome")

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)

Enter a stringWe are learning Python


Orignal string is: We are learning Python
New string is: W r lrnng Pythn

7. Write a program to remove ‘T’ from the string ‘INSTITUTE’.

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

Enter main string My main string


Enter encryption key@$
The encrypted string is M@$y@$ @$m@$a@$i@$n@$
@$s@$t@$r@$i@$n@$g
The string after decryption is My main string

38

You might also like