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

Chapter 09 - String

The document provides an overview of strings in Python, detailing their representation, indexing methods (forward and backward), and immutability. It explains how to create single-line and multi-line strings, as well as string slicing and membership operators. Additionally, it covers string comparison, the use of built-in functions like ord() and chr(), and examples of string expressions.

Uploaded by

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

Chapter 09 - String

The document provides an overview of strings in Python, detailing their representation, indexing methods (forward and backward), and immutability. It explains how to create single-line and multi-line strings, as well as string slicing and membership operators. Additionally, it covers string comparison, the use of built-in functions like ord() and chr(), and examples of string expressions.

Uploaded by

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

1

A String in Python is a collection of characters, of char array


type. In a program sometimes we may need to represent string
of char array type, then we may use this type of data type. A
string in Python will always enclosed in single , double or triple
quotation mark. i.e. ‘VALSAD’ , “WHAT IS YOUR NAME”,
“””ENTER THE NUMBER””” etc.

Here, values VALSAD,


WHAT IS %%%, How Are
You are referred as
e.g. STRING Literals.
X= ‘VALSAD’
Y = “WHAT”
Print(“””% % %”””)
2
A String in Python is represented and accessed in memory by
adding an additional integer number called an index or subscript.
Python supports two ways indexing or subscripting techniques,
namely forward indexing and backward indexing. In forward
indexing each character in a string value will be assigned an
index starting from 0 in left to right order. the last character in a
string value will have index as string length-1. Consider following
example.
e.g. LEFT RIGHT

X= ‘VALSAD’
Characters
of the
String Value
V A L S A D
Forward
Indexing 0 1 2 3 4 5

3
In backward indexing each character in a string value will be
assigned an index starting from -1 in right to left order. the last
character in a string value will have starting index as string -1.
Consider following example.

e.g.
X= ‘VALSAD’
LEFT RIGHT

Characters
of the
String Value
V A L S A D
Backward
Indexing -6 -5 -4 -3 -2 -1

4
In Python when we access characters with in string then it must
be with in the forward or backward indices range. If we try to
access the element / character from the string beyond it’s
forward/ backward indices then Python will generate index out of
bound error. In Python to access individual characters from the
string we use StringVariable[ ], the square brackets accepts an
index of the character with in a string value.

Here we try to access 6th


index element, which
doesn’t exists, So error
is generated. 5
In Python strings are immutable i.e. value once assigned to a
string variable will never change during program’s execution.
Here we have replaced
the value of variable X, it
is allowed for a
immutable type

Here we are changing


the character at 0th index
with variable X, which is
not allowed for an
immutable type. 6
The String literal in python can be represented in different ways,
according its specification its usage it different. These ways to
specify strings are as follows.

String
Literals

Single Line Multiline


Strings Strings
7
C2.A Single Line String:
The strings you create by enclosing text in single quotes (‘ ’) or
double (“ ”) are normally single line strings, i.e. they must
terminate in one line.

In this examples first two


variable declaration for a
single line string is correct,
but the last variable A is
incorrect as single line
strings incorrectly
terminated

8
C2.B Multi Line String:
The multi line strings contains multiple lines of text with in it. The
multiple lines of string can be stored or obtained using one of the
following ways.
1) By adding backslash at the end of normal single / double
quote
In this method we need to add just add back slash in order to

Here, variable A is
incorrect , variable B,C
are correct as its
indicating multiple lines
of string using back
slash.
9
2) By typing the text in triple quotation marks.

Here, variable A and B


are multi line strings
declared using triple
quotation marks.

10
Remark-1:
When we specify the multiple line string using triple quotation
marks, then for every ‘Enter’ key press it puts up an additional
character ‘\n’ with in the string. Where as backslash method
will not add any additional character in existing string.
Consider the following example

Here, variable A stores


extra \n character as
Enter Key is pressed.
Variable B, C doesn’t
contain any additional
characters as lines
ended with back slash
(/)
11
Remark-2:
Python determines the size of the string as the count of
characters in the string. For e.g. size of string “abc” is 3 and
‘hello’ is 5. But if your strings literal has an escape sequence
contained within it, then make sure to count the escape
sequence as on character. Consider the following example.

Here, Observe different


sizes of the strings
values assigned to
variable A.

12
Remark-3:
Python determines some characters are reserved and having
its specific use with in the string value. These special
reserved characters are as follows…

13
Remark-4:
In Python you can type single or double quote with in a string
value directly. For the same you doesn’t need to use any
escape sequence character. Consider the following example.

14
In Immutable type changing value not in place, i.e. changing the
memory location for a variable is allowed.
e.g.
X=“VALSAD”

The memory representation of the above string will as follows.

LValues
V A L S A D
RValues
208 210 212 214 216 218

X [0] X [0] X [0] X [0] X [0] X [0]

15
Now, if we specify a statement which changes the memory
location of the variable X it will be allowed.

X=“VAPI”

The memory representation of the above string will as follows.

LValues
V A P I
RValues
310 312 314 316 318 320

X [0] X [1] X [2] X [3]

16
In immutable type, when we change
the value in place i.e. we are
changing the value of the same
memory location the it will not be
allowed and error will be generated.

17
In Python a Traversing a string refers to process, visit each and
every character exists in a string value , starting from the 1st most
character to the last most character. In Traversing we can
process one character of the string at a time. The easiest way to
traverse a string is to use for loop to iterate through each
character of the string. Consider following example.

Here for loop traverse in


a string variable Name,
each character is
processed from 1st to
last one.

18
A String expression in Python is a valid combination of string
literals or operands and any two arithmetic operators i.e.
either + or *. When we use + operator between two literals
and then the result will be the concatenated strings. When we
use * operator and one literal, operand will be staring type
where as the other literal or operand will be of integer type
only. Consider the following examples.

Here “STR-1” + “STR-2” is a


string expression and the
result will be concatenation of
two strings.
19
Here “STR-1” * 3 or 3 * “STR-
1” is a string expression and
the result will be repetition
string STR-1 three times..

Here “STR-1” * “STR-2” is a


string expression , but this
expression violating string
expression rules i.e. form
multiplication one literal/
variable must be string and
other must be integer. 20
Therefore error .
Membership operators are operators used to validate the
membership of a value. It test for membership in a sequence,
such as strings, lists, or tuples. in operator : The ‘in’ operator is
used to check if a value exists in a sequence or not. Evaluates
to true if it finds a variable in the specified sequence and false
otherwise. ‘not in’ operator- Evaluates to true if it does not finds
a variable in the specified sequence and false otherwise. In
String membership operators are case sensitive.
Here membership operators as
used to search a string
member of other string or not.

21
Python’s standard comparison operator i.e. all relational
operators (<,>,<=,>=,!= & ==) can be applied to strings also.
The comparison using these operators are based on the
standard character-by-character comparison rules for Unicode
encoding scheme. The == and != operators are easy to
understands and recognize as either true or false, but when
comparison takes place using <, >, <= and >= then the
comparison will takes place using standard character-by-
character comparison rules for Unicode encoding scheme (i.e.
character’s ordinal value). Some common characters and their
ordinal values are as follows.
Characters Ordinal Values Range
0 TO 9 48 TO 57
A TO Z 65 TO 90
A to z 97 TO 122
22
Here strings are compared
using == and != operators.
These operators are Case
Sensitive.

Here ordinal value of ‘A‘ is 65


and for ‘A’ its is 97. Hence
based on this values X>Y will
be true and X<Y will be false. 23
Here ordinal values of
‘A’,’B’,’C’ are 65,66 and 67
respectively. Hence based on
this values X>Y will be true
and X<Y will be false.

Here ordinal values of ‘a’, ’b’,


’c’, ’d’ and ‘D’ are 97, 98, 99,
100 and 68 respectively. Hence
based on this values X>Y will
be true and X<Y will be false. 24
Python’s library offers a built in function namely ord() which
accepts ca character and return it’s ordinal value. Consider
following examples.
Ord() function returns values
for ‘A’ and ‘%’.

Always make sure that


you specify single
character in Ord()
function, otherwise it will
generate error.

25
Python’s library offers a built in function namely chr() which
accepts one ordinal number and return it’s corresponding
character. Consider following examples.
chr() function returns
characters for 65 and 37.

Always make sure that


you specify one ordinal
value in chr() function,
otherwise it will generate
error.

26
A String slices in Python refers to a part of the string which is
extracted from another string. It is a string containing some
contagious character of another string. In Python to have a
string slice we must use the syntax as StringVariable[
StartingIndex : EndlingIndex]. When we extract characters using
string slice, it start extracting from starting index characters fro
ending index -1 (i.e. ending index character is always excluded
during string slices). In String Slices we can specify indices
using any string indexing technique i.e. forward indexing or
backward indexing. Consider the following string representation.

e.g.

X=‘Alauddin’ 27
The representation of the above string using forward indexing
inside memory will as follows…

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7

The representation of the above string using backward indexing


inside memory will as follows…

Characters

Backward
A L A U D D I N
Indexing -8 -7 -6 -5 -4 -3 -2 -1

28
e.g.-1

Here X[0 : 8] will extract all


characters between indies 0 to
7.

Extracting Character LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
29
e.g.-2

Here X[0 : 8 : 2] will extract all


characters between indies 0 to
7 by skipping 1 character each
time.

Extracting Character LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
30
e.g.-3

Here X[0 : 3] will extract all


characters between indies 0 to
2.

Extracting Character
LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
31
e.g.-4

Here X[2 : 5] will extract all


characters between indies 2 to
4.

Extracting Character
LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
32
e.g.-5

Here X[ : 7] will extract all


characters between indies 0 to
6. If Starting index is missing
then Python will consider it as
0

Extracting Character LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
33
e.g.-6

Here X[ : 5] will extract all


characters between indies 0 to
4. If Starting index is missing
then Python will consider it as
0.

Extracting Character LEFT To RIGHT order

Characters

Forward
A L A U D D I N
Indexing 0 1 2 3 4 5 6 7
34
e.g.-7

Here X[-7 : -3] will extract all


characters between indies -4
to -7. It will exclude character
as index -3. The order of
extraction will be always from
LEFT TO RIGHT

Extracting Character
LEFT To RIGHT order

Characters

Backward
A L A U D D I N
Indexing -8 -7 -6 -5 -4 -3 -2 -1
35
e.g.-8

Here X[ : : -1] will extract all


characters between indies 0 to
7 from RIGHT to LEFT i.e.
reverse a string.

Extracting Character RIGHT TO LEFT order

Characters

Backward
A L A U D D I N
Indexing -8 -7 -6 -5 -4 -3 -2 -1
36
e.g.-9

Here X[ : : -2] will extract all


characters between indies 0 to
7 from RIGHT to LEFT i.e.
reverse a string, but this will
skip one character each time.

Extracting Character RIGHT TO LEFT order

Characters

Backward
A L A U D D I N
Indexing -8 -7 -6 -5 -4 -3 -2 -1
37
e.g.-10

Here X[0:5] will extract all


characters between indies 0 to
4 from RIGHT to LEFT, but the
string is empty and python will
not generate any error.

Extracting Character RIGHT TO LEFT order

Characters

Forward
Indexing 0 1 2 3 4 5 6 7
38
Python’s also offers many built in functions and methods for
string manipulation. Every string object you create in Python is
actually an instance of String class. The string class allows us to
use readymade methods to perform some simple and
miscellaneous tasks. To use string function using string object we
must use the following syntax.
StringObject.MethodName(Arguments/Parameters)
The built in function offered by string class in Python are as
follows…
capatalize() find() isalnum() isalpha() isdigit() islower()

isspace() isupper() lower() upper() lstrip() rstrip()

39
A. capitalize()
This function doesn’t accepts any argument and return a new
string with its first character capitalized. Consider the following
example.

Str is capitalized using


capitalize() function.

40
B. find(String, Starting Index, Ending Index)
This function returns lowest index in the string where the
substring found with in the slice range from starting index and
ending index.. If the string doesn’t exists then this function return
-1. Consider the following example.

find() function operates on


different string values and
return the result accordingly.

41
C isalnum()
This function returns true if all characters with in a string object
are from alphanumeric category i.e. A-Z, a-z and 0-9. Otherwise
it returns false. Consider following example.

isalnum() function operates on


different string values and
return the result accordingly.

42
D isalpha()
This function returns true if all characters with in a string object
are from alphabets category i.e. A-Z, a-z. Otherwise it returns
false. Consider following example.

isalpha() function operates on


different string values and
return the result accordingly.

43
D isdigit()
This function returns true if all characters with in a string object
are from number category i.e. 0-9. Otherwise it returns false.
Consider following example.

isdigit() function operates on


different string values and
return the result accordingly.

44
E islower()
This function returns true if all characters with in a string object
are from lower case letters category i.e. a-z. Otherwise it returns
false. Consider following example.

islower() function operates on


different string values and
return the result accordingly.

45
F isspace()
This function returns true if all characters with in a string object
are from space (blank spaces) category. Otherwise it returns
false. Consider following example.

isspace() function operates on


different string values and
return the result accordingly.

46
G isupper()
This function returns true if all characters with in a string object
are from upper case alphabets category. Otherwise it returns
false. Consider following example.

isupper() function operates on


different string values and
return the result accordingly.

47
H lower()
This function returns a new string after converting all of its upper
case letter to lowercase. Consider following example.

lower() function operates on


different string values and
return the result accordingly.

48
I upper()
This function returns a new string after converting all of its lower
case letter to upper case. Consider following example.

upper() function operates on


different string values and
return the result accordingly.

49
J lstrip()
This function returns a new string after removing the leading
spaces from the existing string in absence of any argument. But
if we specify the argument as string then from left side all
possible combination of the specified argument will be removed
from left side of the existing string. This method is case sensitive.

lstrip() function operates on


different string values and
return the result accordingly.

50
lstrip() function operates on a
string value “tears” and return
the result accordingly and
removes any combination of
characters from word “tears”
from left side of the string. The
combination will be t, te, tea,
tear, tears, e, et etc…

51
I rstrip()
This function returns a new string after removing the trailing
spaces from the existing string in absence of any argument. But
if we specify the argument as string then from right side all
possible combination of the specified argument will be removed
from right side of the existing string. This method is case
sensitive.

rstrip() function operates on


different string values and
return the result accordingly.

52
rstrip() function operates on a
string value “tears” and return
the result accordingly and
removes any combination of
characters from word “tears”
from right side of the string.
The combination will be t, te,
tea, tear, tears, e, et etc…

53

You might also like