0% found this document useful (0 votes)
12 views5 pages

Chapter 5 String Manipulation

..

Uploaded by

editingbylove
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views5 pages

Chapter 5 String Manipulation

..

Uploaded by

editingbylove
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

S tring Manipulation

Topics
5.1 Introduction
5.2 Traversing a String
5.3 String Operators
5.4 String Slices
5.5 String Functions and Methods

5.1 Introduction
Strings are sequence of characters, where each character has a unique position-id/index.
Index 0 1 2 3 4 5 6
(left to right)
word a m a z i n g
Index -7 -6 -5 -4 -3 -2 -1
(Right to Left)

Python strings are characters enclosed in quotes of any type- ‘ ‘, “ “, ‘’’ ‘’’.
Python string are immutable.(can never change their value in place(same address))

5.2 Traversing a String


Traversing refers to iterating through the elements of a string, one character at a time.
Actually it is like you are travelling from one city to another city, where city refers a character.
For ex.
name=”your name”
for ch in name:
print (ch,’-‘,end=’ ‘ )
The above code will print
y-o-u-r---n-a-m-e

ex.
WAP to read a string and display it in reverse order.
s1=input(“enter string……….”)
print (“the string”,s1,” in reverse order is:”)
size=len(s1)
for a in range(-1,(-size-1),-1):
print(s1[a])
ex.

1|Page
WAP to display a string in different form.
s1=input(“enter string……….”)
size=len(s1)
i=0
for a in range(-1,(-size-1),-1):
print(s1[i],”\t”,s1[a])
i+=1
Assignment
1. Write a program to find no. of occurrences of character “a” in given string.
2. Write a program to find no. of occurrences of character vowels in given string. It should print
There are 5 a in the given string ‘The fast car can break the barrier.’
There are 4 e in the given string ‘The fast car can break the barrier.’
There are 1 i in the given string ‘The fast car can break the barrier.’
There are 0 o in the given string ‘The fast car can break the barrier.’
There are 0 u in the given string ‘The fast car can break the barrier.’
Total vowels are 10

5.3 String Operators


Basic operators

Basic Meaning example Caution


operators
+ concatenation ‘2’+’5’=’25’ or “tea”+”4”+”u”=”tea4u” “tea”+4= errors
TypeError:Cannot
concatenate ‘str’ and ‘int’
* replication 3*”go!”=go! go! go! “2”*”come”
TypeError:one value
should be ‘int’
in True if exits “a” in “cat” Case sensitive
not in True if not exist “help” not in “HELPAGE” Case sensitive

Comparison Operators
Internally Python compares using Unicode values(called ordinal value)
Common characters and their ordinal values
Characters Ordinal values
‘0’ to ‘9’ 48 to 57
‘A’ to ‘Z’ 65 to 90
‘a’ to ‘z’ 97 to 122
To know the corresponding ordinal value
>>>ord(‘A’)
2|Page
>>>65

To know the corresponding character value


>>>chr(65)
>>>”A”

“a”==”a” will give true


“xyz”==”xyz” will give true
“a”!=”ab” will give true
“A”!=”a” will give true
“abcd”>”abcD” will give true why ? explain!

5.4 String Slices (part of the string)


See this old example
Index 0 1 2 3 4 5 6
(left to right)
word a m a z i n g
Index -7 -6 -5 -4 -3 -2 -1
(Right to Left)

word[0:7] will give ‘amazing’


word[0:3] will give ‘ama’ letters from index 0 to 3-1

find answer for the following string slices

word[2:5]
word[-7:-3]
word[-5:-1]

if ,however,you skip either of the begin index or last, python will consider the limits of the string i.e.,for
missing begin index, it will consider 0 and for last value, it will consider length of the string.
Find output
word[:7]
word[:5]
word[3:]
word[5:]

WAP to print following pattern without using nested loop


#
##

3|Page
###
####
#####

solution
s='#'
p=""
for a in range(5):
p+=s
print(p)

5.5 String Functions and Methods


Built-in function can be applied to string as per following syntax:
<string object>.<method name>()
For example
>>> "sudhir".capitalize()
'Sudhir'

Function Example and output


[Link]() >>> "sudhir".capitalize()
'Sudhir'
[Link](sub,start,end) >>> "computer science".find('sci')
9
>>> "computer science".find('sci',4,10)
-1
(return -1 if not found)

>>> "computer science".find('sci',4,15)


9
[Link]() Returns True if the charactersin the string are
alphanumeric(alphabet or numbers)
[Link]() True, if all characters are alphabets.
[Link]() True, if all characters are digits.
[Link]() True, if all characters are in lower case.
[Link]() True, if there are only space.
[Link]() True, if all characters are in upper case.
[Link]() Returns a copy of character in lower case.
[Link]() Returns a copy of character in upper case.
[Link]([char]) Remove matched char from left.
[Link]([char]) Removed matched character from right.

4|Page
Assignment
1. WAP to read a line and print its statistics like:
Number of uppercase letters:
Number of lowercase letters:
Number of alphabets:
Number of digits:

2. WAP to read a line and a [Link] should then display numbers of occurrences of the given substring
in the line.
Solution
count=pos=start=0
line=input("enter a line")
word=input("enter a word")
lline=len(line)
lword=len(word)
end=lline

while True:
pos=[Link](word,start,end)
if(pos!=-1):
count=count+1
start=pos+lword
else:
break;
if(start>lline):
break;
print("number of occurrences of ",word,”:”, count)

program . write a program that reads a string and then prints a string that capitalizes every other letter in the
string e.g., passion becomes PaSsIoN

s1=input("Enter a string")
s2=""
for a in range(0,len(s1),2):
s2=s2+s1[a].upper()
if a<(len(s1)-1):
s2=s2+s1[a+1]
print ("original string:",s1)
print("changed string:",s2)

5|Page

You might also like