[go: up one dir, main page]

0% found this document useful (0 votes)
6 views44 pages

Ch7. Strings: Dr. Tulika Assistant Professor Department of Computer Science Miranda House

The document provides an overview of strings in Python, explaining that strings are sequences of characters treated as objects of the str class. It covers string creation, indexing, immutability, and various built-in functions and operators for string manipulation, such as slicing, concatenation, and formatting. Additionally, it discusses methods for testing, searching, and formatting strings, as well as examples of their usage.
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)
6 views44 pages

Ch7. Strings: Dr. Tulika Assistant Professor Department of Computer Science Miranda House

The document provides an overview of strings in Python, explaining that strings are sequences of characters treated as objects of the str class. It covers string creation, indexing, immutability, and various built-in functions and operators for string manipulation, such as slicing, concatenation, and formatting. Additionally, it discusses methods for testing, searching, and formatting strings, as well as examples of their usage.
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/ 44

Dr.

Tulika

CH7. STRINGS Assistant Professor


Department of Computer Science
Miranda House
7.1 INTRODUCTION
Characters are building blocks of Python. A program is composed of a sequence of
characters.
When a sequence of characters is grouped together, a meaningful string is created.
Thus, a string is a sequence of characters treated as a single unit.
In many languages, strings are treated as arrays of characters but in Python a string
is an object of the str class.
7.2 STR CLASS
Strings are objects of the str class. We can create a string using the constructor of str
class as:
S1=str() #Creates an Empty string Object
S2=str(“Hello”) #Creates a String Object for Hello
An alternative way to create a string object is by assigning a string value to a
variable.
Example
S1 = “” # Creates an Empty String
S2= “Hello” # Equivalent to S2=str(“Hello”)
All the characters of a string can be accessed at one time using the index operator.
7.3 BASIC INBUILT PYTHON
FUNCTIONS FOR STRING
min() and max() functions to return the largest and smallest character in a string. We
can also use len() function to return the number of characters in a string.
7.4 THE INDEX[] OPERATOR
As a string is a sequence of characters, the characters in a string can be accessed one
at a time through the index operator.
The characters in a string are zero based, i.e. the first character of the string is stored
at the 0th position and the last character of the string is stored at a position one less
than that of the length of the string.
Note: Consider a string of length ‘n’, i.e. the valid indices for such string are from 0 to
n-1. If you try to access the index greater than n-1, Python will raise a ‘string index
out of range’ error.
7.4.1 ACCESSING CHARACTERS VIA
NEGATIVE INDEX
The negative index accesses characters from the end of a string by counting in
backward direction.
The index of the last character of any non-empty string is always -1.
Note:
S[-n] == S[Length _ of(S)-n]
Example:
S=“IIT-Bombay”
>>> S[-3]
>>>‘b’
7.5 TRAVERSING STRING WITH FOR
AND WHILE LOOP
A programmer can use the for loop to traverse all characters in a string.
7.5.1 TRAVERSING WITH A WHILE
LOOP
A programmer can also use the while loop to traverse all the elements of a string.
7.6 IMMUTABLE STRINGS
Character sequences fall into two categories, i.e. mutable and immutable. Mutable
means changeable and immutable means unchangeable. Hence, strings are immutable
sequences of characters.
Python uses one object for each string which has the same content.
7.7 THE STRING OPERATORS
String contains the slicing operator and the slicing with step size parameter is used to
obtain the subset of a string. It also has basic concatenation ‘+’, ‘ in’ and repetition ‘*’
operators.
7.7.1 The String Slicing Operator [start: end]
The slicing operator returns a subset of a string called slice by specifying two indices,
viz. start and end. The syntax used to return a subset of a string is:
Name_of_Variable_of_a_String[ Start_Index: End_Index]
Example
>>> S=“IIT-BOMBAY”
>>> S[4:10] #Returns a Subset of a String
‘BOMBAY’
The S[4:10] returns a subset of a string starting from start index, i.e. 4 to one index
less than that of end parameter of slicing operation, i.e. 10 - 1 = 9.
>>> S[:-1]
#start with the character stored at index 0 & exclude the last character stored
at index -1.
‘IIT-MADRA’
7.7.2 STRING SLICING WITH STEP
SIZE
7.7.3 THE STRING +, * AND IN
OPERATORS
1. The + Operator: The concatenation operator ‘+’ is used to join two strings.
Example:
>>> S1=“IIT” #The String “IIT” assigned to S1
>>> S2=“Delhi” #The String “Delhi” assigned to S1
>>> S1+S2
‘IIT Delhi’
2. The * Operator: The multiplication (*) operator is used to concatenate the same
string multiple times. It is also called repetition operator.
Example:
>>> S1=“Hello”
>>> S2=3*S1 #Print the String “Hello” three times
>>> S2
‘HelloHelloHello’
3. The in and not in Operator: Both Operators in and not in are used to check whether
a string
is present in another string.
Example:
>>> S1=“Information Technology” #Check if the string “Technology” is present
in S1
>>> “Technology” in S1
True #Check if the string “Technology” is present in S1
>>> “Engineering” in S1
False
>>> S1=”Information Technology” # Check if the string “Hello” is not present in S1
>> “Hello” not in S1
True
7.8 STRING OPERATIONS
7.8.1 String Comparison
Operators such as ==,<,>,<=,>=and != are used to compare the strings. Python
compares strings by comparing their corresponding characters.
Example
>>> S1=“abcd”
>>> S2=“ABCD”
>>> S1>S2
True
Python compares the numeric value of each character. In the above example, the
numeric value, i.e. ASCII value of ‘a’ is 97 and ASCII numeric value of ‘A’ is 65. It
means 97 > 65. Thus, it returns True. However, character by character comparison
goes on till the end of the string.
>>> S1=“abc”
>>> S2=“abc”
>>> S1==S2
True
>>> S1=“ABC”
>>> S2=“DEF”
>>> S1>S2
False
>>> S1=“AAA”
>>> S2=“AAB”
>>> S2>S1
True
>>> S1=“ABCD”
>>> S2=“abcd”. upper()
>>> S2
‘ABCD’
>>> S1>S2
False
>>> S1>=S2
True
7.8.2 THE STRING .FORMAT()
METHOD()
In Python 2 and 3, programmers can include %s inside a string and follow it with a list
of values for each %.
Example
>>> “My Name is %s and I am from %s”%(“JHON”,”USA”)
‘My Name is JHON and I am from USA’
Python 3 has added a new string method called format() method. Instead of % we
can use {0}, {1} and so on. The syntax for format() method is:
template.format(P0,P1,…………,k0=V0,K1=V1…}
the arguments to the .format() method are of two types. It consists of zero or more
positional arguments Pi followed by zero or more keyword arguments of the form,
Ki=Vi.
Example
>>> ‘{} plus {} equals {}’.format(4,5,’Nine’)
‘4 plus 5 equals Nine’
Explanation
The format() method is called on the string literal with arguments 4,5 and ‘Nine’. The
empty {} are replaced with the arguments in order. The first {} curly bracket is
replaced with the first argument and so on. By default, the index of the first argument
in format always start from zero. One can also give a position of arguments inside the
curly brackets.
Example
>>> “My Name is {0} and I am from {1}”.format(“Milinda”,”USA”)
‘My Name is Milinda and I am from USA’
Keyword Argument and format() Method
We can also insert text within curly braces along with numeric indexes. However, this
text has to match keyword arguments passed to the format() method.
Example
>>> “I am {0} years old. I Love to work on {PC} Laptop”.format(25,PC=”APPLE”)
‘I am 25 years old. I Love to work on APPLE Laptop’
7.8.3 THE SPLIT() METHOD
The split() method returns a list of all the words in a string. It is used to break up a
string into smaller strings.
>>>Str1=“C C++ JAVA Python” #Assigns names of Programming languages to Str1
>>>Str1.split()
[‘C’, ‘C++’, ‘JAVA’, ‘Python’]
Note: The split() method can be called without arguments. If it is called without a delimiter,
then
by default the space will act as a delimiter.
7.8.4 TESTING STRING
A string may contain digits, alphabets or a combination of both of these. Thus, various
methods are available to test if the entered string is a digit or alphabet or is
alphanumeric.
7.8.5 SEARCHING SUBSTRING IN A
STRING
7.8.6 METHODS TO CONVERT A
STRING INTO ANOTHER STRING
7.8.7 STRIPPING UNWANTED
CHARACTERS FROM A STRING

Note: Characters such as ‘’, \f,\r, and \n are called white space characters.
str rstrip() : Returns a string with the trailing white space characters removed.

txt = " banana "

x = txt.rstrip()

print("of all fruits", x, "is my favorite")


7.8.8 FORMATTING STRING
str center(int width) : Returns a copy of the string centered in a field of the
given width.
str ljust(int width) : Returns a string left justified in a field of the given width.
str rjust(int width) : Returns a string right justified in a field of the given width.
7.8.9 SOME PROGRAMS ON
STRING

You might also like