0% found this document useful (0 votes)
33 views

PPS U4 DIT Andy@$

This document discusses strings in Python. It covers: 1) How to create strings using single, double or triple quotes and accessing characters using indexes and slicing. Strings are immutable in Python. 2) Common string operations like concatenation, append, repetition and slicing. 3) That Python strings are immutable so modifying a string creates a new one at a different memory location. 4) Different ways of string formatting like using % operator and format sequences. 5) Some common string methods like capitalize(), isalnum(), isalpha() along with examples.

Uploaded by

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

PPS U4 DIT Andy@$

This document discusses strings in Python. It covers: 1) How to create strings using single, double or triple quotes and accessing characters using indexes and slicing. Strings are immutable in Python. 2) Common string operations like concatenation, append, repetition and slicing. 3) That Python strings are immutable so modifying a string creates a new one at a different memory location. 4) Different ways of string formatting like using % operator and format sequences. 5) Some common string methods like capitalize(), isalnum(), isalpha() along with examples.

Uploaded by

sticlipsyt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

PPS Unit-VI DIT,Pimpri

Dr. D. Y. PATIL INSTITUTE OF TECHNOLOGY, PIMPRI, PUNE-18


Department of First Year Engineering
Programming and Problem Solving
Unit- 4 Notes
_________________________________________________________________________
Unit IV: Strings
4.1 Strings and Operations

Q 1. What is String? With the help of example explain how we can create string
variable in python.
Ans:
 Strings data type is sequence of characters, where characters could be letter, digit,
whitespace or any other symbol.
a. Creation of Strings:
o Strings in Python can be created using single quotes or double quotes or even
triple quotes.
o Example:
string1 = 'Welcome' # Creating a String with single Quotes
string2 = "Welcome" # Creating a String with double Quotes
string3 = '''Welcome''' # Creating a String with Triple Quotes

b. Accessing strings:
o In Python, individual characters of a String can be accessed by using the method
of Indexing or range slice method [:].
o Indexing allows negative address references to access characters from the back
of the String, e.g. -1 refers to the last character, -2 refers to the second last
character and so on.

String W E L C O M E
Indexing 0 1 2 3 4 5 6
Negative Index -7 -6 -5 -4 -3 -2 -1

1
Andy@$
PPS Unit-VI DIT,Pimpri

o Example:
string = 'Welcome'
print(string[0]) #Accessing string with index
print(string[1])
print(string[2])
print(srting[0:2]) #Accessing string with range slice
method

Output:
w
e
l
wel

c. Deleting/Updating from a String:


o In Python, updating or deletion of characters from a String is not allowed as
Strings are immutable.
o Although deletion of entire String is possible with the use of a built-in del
keyword.
o Example:
string='welcome'
del string

Q 2. Explain Operations on string.


Ans:
Operation Description Example Output
Concatenation(+) -It joins two strings x="Good" Good Morning
and returns new list. y="Morning"
z=x+y
print(z)

2
Andy@$
PPS Unit-VI DIT,Pimpri

Append (+=) -Append operation x="Good" Good Morning


adds one string at y="Morning"
the end of another x+=y
string print(x)
Repetition(*) -It repeats elements x="Hello" HelloHello
from the strings n y=x*2
number of times print(y)
Slice [] - It will give you x="Hello" e
character from a print(x[1])
specified index.

Range slice[:] -It will give you x="Hello" He


characters from print(x[0:2])
specified range slice.

4.2 Strings are immutable


Q 3. Python strings are immutable. Comment on this.
Ans:
 Python Strings are immutable, which means that once it is created it cannot be changed.
 Whenever you try to change/modify an existing string, a new string is created.
 As every object (variable) is stored at some address in computer memory.
 The id() function is available in python which returns the address of object(variable) in
memory. With the help of memory locations/address we can see that for every
modification, string get new address in memory.
 Here is the example to demonstration the address change of string after modification.
# prints string1 and its address
string1="Good"
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

3
Andy@$
PPS Unit-VI DIT,Pimpri

# prints string2 and its address


string2="Morning"
print("String2 value is: ",string2)
print("Address of string2 is: ",id(string2)

#appending string1 to string2


string1+= string2
print("String1 value is: ",string1)
print("Address of string1 is: ",id(string1)

Output:
String1 value is: Good
Address of String1 is: 1000

String2 value is: Morning


Address of String1 is: 2000

String1 value is: GoodMorning


Address of String1 is: 3000

 From the above output you can see string1 has address 1000 before modification. In
later output you can see that string1 has new address 3000 after modification.
 It is very clear that, after some operations on a string new string get created and it has
new memory location. This is because strings are unchangeable/ immutable in nature.
Modifications are not allowed on string but new string can be created at new address
by adding/appending new string.

4.3 Strings formatting operator


Q 4. Explain various ways of string formatting with example.
Ans:
 In python, % sign is a string formatting operator.

4
Andy@$
PPS Unit-VI DIT,Pimpri

 The % operator takes a format string on the left and the corresponding values in a
tuple on the right.
 The format operator, % allows users to replace parts of string with the data stored in
variables.
 The syntax for string formatting operation is:
"<format>" % (<values>)
 The statement begins with a format string consisting of a sequence of characters and
conversion specification.
 Following the format string is a % sign and then a set of values, one per conversion
specification, separated by commas and enclosed in parenthesis.
 If there is single value then parenthesis is optional.
 Following is the list of format characters used for printing different types of data:
Format Purpose
Symbol
%c Character
%d or %i Signed decimal integer
%s String

%u Unsigned decimal integer

%o Octal integer

%x or %X Hexadecimal integer

%e or %E Exponential notation

%f Floating point number

%g or %G Short numbers in floating point or exponential notation

Example: Program to use format sequences while printing a string.


name="Amar"
age=8
print("Name = %s and Age = %d" %(name,age))
print("Name = %s and Age = %d" %("Ajit",6))

5
Andy@$
PPS Unit-VI DIT,Pimpri

Output:
Name = Amar and Age = 8
Name = Ajit and Age = 6

In the output, we can see that %s has been replaced by a string and %d has been replaced by
an integer value.

4.4 Built-in String methods and functions


Q 5. List and explain any 5 string methods.
Or
Q. Explain the use of ______ ( ) with the help of an example.
Ans.
Sr. Function Usage Example
No.
1 capitalize() This function is used to capitalize str="hello"
first letter of string. print(str.capitalize())
output:
Hello
2 isalnum() Returns true if string has at least 1 message="JamesBond007"
character and every character is print(message.isalnum())
either a number or an alphabet and output:
False otherwise. True
3 isalpha() Returns true if string has at least 1 message="JamesBond007"
character and every character is an print(message.isalpha())
alphabet and False otherwise. output:
False
4 isdigit() Returns true if string has at least 1 message="007"
character and every character is a print(message.isdigit())
digit and False otherwise. output:
True
5 islower() Returns true if string has at least 1 message="Hello"

6
Andy@$
PPS Unit-VI DIT,Pimpri

character and every character is a print(message.islower())


lowercase alphabet and False output:
otherwise. False
6 isspace() Returns true if string contains only message=" "
white space character and False print(message.isspace())
otherwise. output:
True
7 isupper() Returns true if string has at least 1 message="HELLO"
character and every character is an print(message.isupper())
uppercase alphabet and False output:
otherwise. True
8 len(string) Returns length of the string. str="Hello"
print(len(str))
output:
5
9 zfill(width) Returns string left padded with str="1234"
zeros to a total of width characters. print(str.zfill(10))
It is used with numbers and also output:
retains its sign (+ or -). 0000001234
10 lower() Converts all characters in the string str="Hello"
into lowercase. print(str.lower())
output:
hello
11 upper() Converts all characters in the string str="Hello"
into uppercase. print(str.upper())
output:
HELLO
12 lstrip() Removes all leading white space in str=" Hello"
string. print(str.lstrip())
output:
Hello

7
Andy@$
PPS Unit-VI DIT,Pimpri

13 rstrip() Removes all trailing white space in str=" Hello "


string. print(str.rstrip())
output:
Hello
14 strip() Removes all leading white space str=" Hello "
and trailing white space in string. print(str.strip())
output:
Hello
15 max(str) Returns the highest alphabetical str="hello friendz"
character (having highest ASCII print(max(str))
value) from the string str. output:
z
16 min(str) Returns the lowest alphabetical str="hellofriendz"
character (having lowest ASCII print(min(str))
value) from the string str. output:
d
17 replace(old,new[, max]) Replaces all or max (if given) str="hello hello hello"
occurrences of old in string with print(str.replace("he","Fo"))
new. output:
Follo Follo Follo
18 title() Returns string in title case. str="The world is beautiful"
print(str.title())
output:
The World Is Beautiful
19 swapcase() Toggles the case of every character str="The World Is
(uppercase character becomes Beautiful"
lowercase and vice versa). print(str.swapcase())
output:
tHE wORLD iS
bEAUTIFUL
20 split(delim) Returns a list of substrings str="abc,def, ghi,jkl"

8
Andy@$
PPS Unit-VI DIT,Pimpri

separated by the specified print(str.split(','))


delimiter. If no delimiter is output:
specified then by default it splits ['abc', 'def', ' ghi', 'jkl']
strings on all whitespace
characters.
21 join(list It is just the opposite of split. The print('-'.join(['abc', 'def', '
function joins a list of strings using ghi', 'jkl']))
delimiter with which the function output:
is invoked. abc-def- ghi-jkl
22 isidentifier() Returns true if the string is a valid str="Hello"
identifier. print(str.isidentifier())
output:
True
23 enumerate(str) Returns an enumerate object that str="Hello World"
lists the index and value of all the print(list(enumerate(str)))
characters in the string as pairs. output:
[(0, 'H'), (1, 'e'), (2, 'l'), (3,
'l'), (4, 'o'), (5, ' '), (6, 'W'),
(7, 'o'), (8, 'r'), (9, 'l'), (10,
'd')]

4.5 Slice operation


Q 6. What is slice operation? Explain with example.
Ans.
Slice: A substring of a string is called a slice.
A slice operation is used to refer to sub-parts of sequences and strings.
Slicing Operator: A subset of a string from the original string by using [] operator
known as Slicing Operator.

9
Andy@$
PPS Unit-VI DIT,Pimpri

Indices in a String

Index from
P Y T H O N
the start
0 1 2 3 4 5
-6 -5 -4 -3 -2 -1

Index from
Syntax:
the end
string_name[start:end]
where start- beginning index of substring
end -1 is the index of last character

Program to demonstrate slice operation on string objects


str=”PYTHON”
print(“str[1:5]= “, str[1:5]) #characters start at index 1 and extending upto index 4
# but not including index 5
print(“str[ :6]= “, str[ :6]) # By defaults indices start at index 0
print(“str[1: ]= “, str[1: ]) # By defaults indices ends upto last index
print(“str[ : ]= “, str[ : ]) # By defaults indices start at index 0 and end upto last
#character in the string
#negative index
print(“str[-1]= “, str[ -1]) # -1 indicates last character
print(“str[ :-2 ]= “, str[ : -2]) #all characters upto -3
print(“str[ -2: ]= “, str[ -2: ]) #characters from index -2
print(“str[-5 :-2 ]= “, str[ -5: -2]) # characters from index -5 upto character index -3

OUTPUT
str[1:5]= YTHO
str[ :6]= PYTHON
str[1: ]= YTHON
str[ : ]= PYTHON

10
Andy@$
PPS Unit-VI DIT,Pimpri

str[-1]= N
str[ :-2 ]= PYTH
str[ -2: ]= ON
str[-5 :-2 ]= YTH

Specifying Stride while Slicing Strings


 In the slice operation, you can specify a third argument as the stride, which refers
to the number of characters to move forward after the first character is retrieved
from the string.
 The default value of stride is 1, i.e. where value of stride is not specified, its
default value of 1 is used which means that every character between two index
number is retrieved.
Program to use slice operation with stride
str=” Welcome to the world of Python“
print(“str[ 2: 10]= “, str[2:10]) #default stride is 1
print(“str[ 2:10:1 ]= “, str[2:10:1]) #same as stride=1
print(“str[ 2:10:2 ]= “, str[2:10:2]) #skips every alternate character
print(“str[ 2:10:4 ]= “, str[2:10:4]) #skips every fourth character

OUTPUT
str[ 2: 10]=lcome to
str[ 2: 10]= lcome to
str[ 2:10:2 ]=loet
str[ 2:10:4 ]=l
 Whitespace characters are skipped as they are also part of the string.

4.6 ord() and chr() functions
Q 7.Write a short note on ord() and chr() functions
Ans.
 The ord() function return the ASCII code of the character

11
Andy@$
PPS Unit-VI DIT,Pimpri

 The chr() function returns character represented by a ASCII number.

ch=’R’ print(chr(82)) print(chr(112)) print(ord(‘p’))


print(ord(ch))

OUTPUT OUTPUT OUTPUT OUTPUT


82 R p 112

4.7 in and not in operators


Q 8.Write a short note on in and not in operators
OR
Q.With the help of example, explain significance of membership operators.
Ans.
 in and not in operators can be used with strings to determine whether a string is
present in another string. Therefore the in and not in operator is known as
membership operators.

 For example:
str1=” Welcome to the world of Python!!!“ str1=” This is very good book“
str2=”the” str2=”best”
if str2 in str1: if str2 in str1:
print(“found”) print(“found”)
else: else:
print(“Not found”) print(“Not found”)

OUTPUT OUTPUT
Found Not found

 You can also use in and not in operators to check whether a character is present in a
word.
 For example:
‘u‘ in “starts” ‘v‘ not in “success”

12
Andy@$
PPS Unit-VI DIT,Pimpri

OUTPUT OUTPUT
False True

4.8 Comparing strings


Q 9. Explain string comparison operator with example?
Ans.
 Python allows us to combine strings using relational (or comparison) operators such
as >, <, <=,>=, etc.
 Some of these operators along with their description and usage are given as follows:
Operator Description Example
== If two strings are equal, it returns True. >>>”AbC”==”AbC”
True
!= or <> If two strings are not equal, it returns True. >>>”AbC”!=”Abc”
True
> If the first string is greater than the second, it >>>”abc”>”Abc”
returns True. True
< If the second string is greater than the first, it >>>”abC”<”abc”
returns True. True
>= If the first string is greater than or equal to >>>”aBC”>=””ABC”
the second, it returns True. True
<= If the second string is greater than or equal to >>>”ABc”<=”ABc”
the first, it returns True. True

 These operators compare the strings by using ASCII value of the characters.
 The ASCII values of A-Z are 65-90 and ASCII code for a-z is 97-122.
 For example, book is greater than Book because the ASCII value of ‘b’ is 98 and ‘B’
is 66.

String Comparison Programming Examples: (Any one)


 There are different ways of comparing two strings in Python programs:

13
Andy@$
PPS Unit-VI DIT,Pimpri

 Using the ==(equal to) operator for comparing two strings:


 If we simply require comparing the values of two variables then you may use
the ‘==’ operator.
 If strings are same, it evaluates to True, otherwise False.

 Example1:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

Output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

 Example2(Checking Case Sensitivity):


first_str='Kunal works at PHOENIX'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by ==
if first_str==second_str:
print("Both Strings are Same")
else:
print("Both Strings are Different")

14
Andy@$
PPS Unit-VI DIT,Pimpri

Output:
First String: Kunal works at PHOENIX
Second String: Kunal works at Phoenix
Both Strings are Different

 Using the !=(not equal to) operator for comparing two strings:
 The != operator works exactly opposite to ==, that is it returns true is both
the strings are not equal.
 Example:
first_str='Kunal works at Phoenix'
second_str='Kunal works at Phoenix'
print("First String:", first_str)
print("Second String:", second_str)
#comparing by !=
if first_str!=second_str:
print("Both Strings are Different")
else:
print("Both Strings are Same")
output:
First String: Kunal works at Phoenix
Second String: Kunal works at Phoenix
Both Strings are Same

 Using the is operator for comparing two strings:


 The is operator compares two variables based on the object id and returns
True if the two variables refer to the same object.
 Example:
name1=”Kunal”
name2=”Shreya”
print(“name1:”,name1)

15
Andy@$
PPS Unit-VI DIT,Pimpri

print(“name2:”,name2)
print(“Both are same”,name1 is name2)
name2=”Kunal”
print(“name1:”,name1)
print(“name2:”,name2)
print(“Both are same”,name1 is name2)
 Output:
name1=Kunal
name2=Shreya
Both are same False
name1=Kunal
name2=Kunal
Both are same True
 In the above example, name2 gets the value of Kunal and subsequently
name1 and name2 refer to the same object.

4.9 Iterating strings
Q. No.10 How to iterate a string using:
Ans.
i) for loop with example
ii) while loop with example
Ans.

 String is a sequence type (sequence of characters).


 We can iterate through the string using:

i) for loop:
 for loop executes for every character in str.
 The loop starts with the first character and automatically ends when
the last character is accessed.
 Example-

16
Andy@$
PPS Unit-VI DIT,Pimpri

str=”Welcome to python”
for i in str:
print(i,end=’ ’)
Output-
Welcome to Python

ii) while loop:


 We can also iterate through the string using while loop by writing the
following code.
 Example-
message=” Welcome to python”
index=0
while index < len(message):
letter=message[index]
print(letter,end=’ ‘)
index=index+1
Output-
Welcome to Python

 In the above program the loop traverses the string and displays each
letter.
 The loop condition is index < len(message), so the moment index
becomes equal to the length of the string, the condition evaluates to
False, and the body of the loop is not executed.
 Index of the last character is len(message)-1.

4.10 The string module


Q. No. 11 Write a note on string module?
 The string module consists of a number of useful constants, classes and functions.
 These functions are used to manipulate strings.

17
Andy@$
PPS Unit-VI DIT,Pimpri

 String Constants: Some constants defined in the string module are:


 string.ascii_letters: Combination of ascii_lowecase and ascii_uppercase
constants.
 string.ascii_lowercase: Refers to all lowercase letters from a-z.
 string.ascii_uppercase: Refers to all uppercase letters from A-Z.
 string.lowercase: A string that has all the characters that are considered
lowercase letters.
 string.uppercase: A string that has all the characters that are considered
uppercase letters.
 string.digits:Refers to digits from 0-9.
 string.hexdigits: Refers to hexadecimal digits,0-9,a-f, and A-F.
 string.octdigits: Refers to octal digits from 0-7.
 string.punctuation: String of ASCII characters that are considered to be
punctuation characters.
 string.printable: String of printable characters which includes digits, letters,
punctuation, and whitespaces.
 string.whitespace: A string that has all characters that are considered
whitespaces like space, tab, return, and vertical tab.
 Example: (Program that uses different methods such as upper, lower, split, join,
count, replace, and find on string object)
str=”Welcome to the world of Python”
print(“Uppercase-“, str.upper())
print(“Lowercase-“, str.lower())
print(“Split-“, str.split())
print(“Join-“, ‘-‘.join(str.split()))
print(“Replace-“,str.replace(“Python”,”Java”))
print(“Count of o-“, str.count(‘o’))
print(“Find of-“,str.find(“of”))

18
Andy@$

You might also like