Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Unit 1:Chapter 3

Strings
String

Consecutive sequence of characters is known as a string. Strings are amongst the most
popular types in Python. An individual character in a string is accessed using a subscript
(index). The subscript should always be an integer (positive or negative). A subscript starts
from 0.We can create string simply by enclosing characters in quotes. Python treats single
quotes the same as double quotes. Creating strings is as simple as assigning a value to a
variable.

Example

>>>str1 = 'Hello Class'

>>>print (str1)

Hello Class

str2 = "Hello Class"

>>>print (str2)

Hello Class

Accessing Values in Strings


Python does not support a character type; these are treated as strings of length one, thus
also considered a substring. You can create substrings with the slicing notation.

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

String H e l l o C l a s S
Positive Subscript 0 1 2 3 4 5 6 7 8 9 10

Example
For accessing first character
>>>print (str1[0])
H
For accessing fifth character
>>>print (str1[4])
o
Because the subscript always starts with 0 so we are accessing fifth character of the string.

You can do this by placing two indices (separated by a colon) within square brackets like
str[a:b]. The ‘a’ represents the first index of the sliced string and b will be last character -1
i.e (b-1).
>>>print (str1[1:6])
ello
The output includes the space character also but it is not clear in this example. The string
sliced from subscript 1 to subscript 5 it always goes like (last -1).as we have already
discussed.
>>>print (str1[:7])
Hello C
Here the starting subscript is not given so it will start from 0 to sixth subscript.space is
clearly visible in this example.
>>>print (str1[4:] )
o Class
Here the last or ending subscript is not given so, it will go from fourth character to the end of
the string.
>>>print (str1[-4])
l
the negative subscript goes from last to first character and always starts with -1 so str1[-4]
looking for the forth last character of the string.
>>>print (str1[-8:-4]
lo C
here -8 is smaller than -4 so we sliced string from -8 to -4.

>>>print(str1[:-4])

Hello C

As we slice the string with positive subscript we can do same with the negative subscript also
the string has no start subscript so it starts with the lowest negative subscript and move till -
5th subscript.

>>>print(str1[-8:]

lo Class

in this example starting subscript of the substring is given so it starts with it and end with the
end of the string so it will show all the characters stat from -8.
Important points about accessing elements in the strings using subscripts

 Positive subscript helps in accessing the string from the beginning


 Negative subscript helps in accessing the string from the end.
 Subscript 0 or –ve n(where n is length of the string) displays the first element. Example
: A[0] or A[-5] will display „H‟
 Subscript 1 or –ve (n-1) displays the second element.

Creating and initializing strings

A literal/constant value to a string can be assigned using a single quotes, double quotes or
triple quotes.

Enclosing the string in single quotes

Example

>>>print (‘A friend in need is a friend indeed’)

A friend in need is a friend indeed

Example

>>>print(’This book belongs to Raghav\’s sister’)

This book belongs to Raghav’s sister

As shown in above example to include the single quote within the string it should be preceded
by a backslash.

Enclosing the string in double quotes

Example

>>>print(“A room without books is like a body without a soul.”)

A room without books is like a body without a soul.


Enclosing the string in triple quote

Example

>>>life=”””\” Live as if you were to die tomorrow.

Learn as if you were to live forever.\”

---- Mahatma Gandhi “””

>>> print life

” Live as if you were to die tomorrow.

Learn as if you were to live forever.”

---- Mahatma Gandhi “””

Triple quotes are used when the text is multiline.

In the above example, backslash (\) is used as an escape sequence. An escape sequences is
nothing but a special character that has a specific function. As shown above, backslash (\) is
used to escape the double quote.

Escape Character

Following table is a list of escape or non-printable characters that can be represented with
backslash notation. An escape character gets interpreted; in a single quoted as well as double
quoted strings.

Backslash notation Description


\a Bell or alert
\b Backspace
\cx Control-x
\C-x Control-x
\e Escape
\f Formfeed
\M-\C-x Meta-Control-x
\n Newline
\nnn Octal notation, where n is in the range 0.7
\r Carriage return
\s Space
\t Tab
\v Vertical tab
\x Character x
\xnn Hexadecimal notation, where n is in the
range 0.9, a.f, or A.F

Strings are immutable


Strings are immutable means that the contents of the string cannot be changed after it is
created.

Let us understand the concept of immutability with help of an example.

Example

>>>str='Class'

>>>str[2]='p'

TypeError: 'str' object does not support item assignment

Python does not allowthe programmer to change a character in a string. As shown in the
above example, str has the value “Class”. An attempt to replace “a” in the string by ‟p‟
displays a TypeError.

Traversing a string

Traversing a string means accessing all the elements of the string one after the other by using
the subscript. A string can be traversed using: for loop or while loop.

String traversal using for loop

Output
A is assigned a string literal ‟Welcome‟. On execution of the for loop, the characters in the
string are printed till the end of the string is not reached.

String traversal using while loop

Output
A is assigned a string literal „Welcome‟ i is assigned value 0. The len() function calculates
the length of the string. On entering the while loop, the interpreter checks the condition. If
the condition is true, it enters the loop. The first character in the string is displayed. The
value i is incremented by 1. The loop continues till value i is less than len-1. The loop finishes
as soon as the value of I becomes equal to len-1, the loop

String Operators

String operators are the operators which are performed on string variables there are so many
operators which works on string some of these are as follows−

Operator Name Description


+ Concatenation Adds or join two strings
* Repetition Concatenating multiple copies of the same string
[] Slice Gives the character from the given index
[:] Range Slice Gives the characters from the given range
in Membership Returns true if a character exists in the given string
not in Membership Returns true if a character does not exist in the given string
r/R Raw String Suppresses actual meaning of Escape characters. The syntax for
raw strings is exactly the same as for normal strings with the
exception of the raw string operator, the letter "r," which
precedes the quotation marks. The "r" can be lowercase (r) or
uppercase (R) and must be placed immediately preceding the
first quote mark.
% Format Performs String formatting
String Formatting Operator
One of Python's coolest features is the string format operator %. This operator is unique to
strings. Following is a simple example –
>>> print(“ In the month of %s our sales are increased by %d Percent” %( ‘March’,20))
In the above example %s denotes the string and %d denotes the integer input and in the
end of the statement the definition of % has given within the brackets first value is a
string and second value is a integer in at the output the values will be replaced. When
the above code is executed, it produces the following result –
In the month of March our sales are increased by 20 Percent
Here is the list of complete set of symbols which can be used along with % −
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lower case letters)
%X hexadecimal integer (UPPER case letters)
%e exponential notation (with lower case 'e')
%E exponential notation (with UPPER case 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E
Built-in String Methods
Python includes the following built-in methods to manipulate strings –
Let us take example of these functions and the values of str1=”HELLO” and str2=”class”
str3=”Hello Class”
S.No. Methods Description Example
1 capitalize() Returns the exact copy of >>> str2.capitalize()
the string with the first 'Class'
letter in upper case
2 center(width, fillchar) Returns a space-padded >>>str1.center(10,'S')
string with the original 'SSHELLOSSS'
string centered to a total of
width columns.
3 count(str, beg= Counts how many times >>> str1.count("L")
0,end=len(string)) “str” occurs in string or in a 2
substring of string if >>> str1.count("L",2,5)
starting index beg and 2
ending index end are >>> str1.count("L",3,5)
given.(beg and end are 1
optional)
4 find(str, beg=0 The function is used to >>> str1.find("l")
end=len(string)) search the first occurrence -1
of the substring in the given >>> str1.find("L")
string. It returns the index 2
at which the substring
starts. It returns -1 if the
substring does occur in the
string.
5 index(str, beg=0, Same as find(), but raises >>> str1.index("L")
end=len(string)) an exception if str not 2
found. >>> str1.index("l")
Traceback (most recent call
last):
File "<pyshell#65>", line 1, in
<module>
str1.index("l")
ValueError: substring not
found
6 isalnum() Returns True if the string >>>str1.isalnum()
contains only letters and True
digit. It returns False ,If the
string contains any special
character like _ , @,#,* etc.
7 isalpha() Returns True if the string >>> str1.isalpha()
contains only letters. True
Otherwise return False.
8 isdigit() Returns True if the string >>> str1.isdigit()
contains only numbers. False
Otherwise it returns False.
9 islower() Returns True if the string is >>> str1.islower()
in lowercase. False
>>> str2.islower()
True
10 isnumeric() Returns true if a unicode >>> str1.isnumeric()
string contains only numeric False
characters and false
otherwise.
11 isspace() Returns True if the string >>> str1.isspace()
contains only white spaces False
and False even if it contains
one character.
12 istitle() Returns True if the string is >>> str2.istitle()
title cased. Otherwise False
returns >>> str1.istitle()
False False
13 isupper() Returns True if the string is >>> str1.isupper()
in uppercase. True
>>> str2.isupper()
False
14 join(seq) Returns a string in which >>> str1.join(str2)
the string elements have 'cHELLOlHELLOaHELLOsHELLOs'
been joined by a separator.
15 len(string) Returns the length of the >>>len(str1)
string 5
16 ljust(width[, fillchar]) Returns a space-padded >>> str2.ljust(10,'a')
string with the original 'classaaaaa'
string left-justified to a
total of width columns.
17 lower() Returns the exact copy of >>> print(str1)
the string with all the HELLO
letters in >>> str1.lower()
lowercase. 'hello'
18 lstrip() Returns the string after >>> str3.lstrip("Hel")
removing the space(s) on 'o Class'
the left of the string..
19 rstrip() Returns the string after >>> str3.rstrip("Hel")
removing the space(s) on 'Hello Class'
the right of the string. >>> str3.rstrip("as")
'Hello Cl'
20 max(str) Returns the max >>> max(str1)
alphabetical character from 'O'
the string str.
21 min(str) Returns the min >>> min(str1)
alphabetical character from 'E'
the string str.
22 replace(old, new [, The function replaces all >>> str1.replace('O','class')
max]) the occurrences of the old 'HELLclass'
string with the new string
23 rjust(width,[, fillchar]) Returns a space-padded >>> str2.rjust(10,'a')
string with the original 'aaaaaclass'
string right-justified to a
total of width columns.
24 split(str="", The function splits the >>> str3.split('l',3)
num=string.count(str)) string into substrings using ['He', '', 'o C', 'ass']
the separator. The second
argument is optional and its
default value is zero. If an
integer value N is given for
the second argument, the
string is split in N+1 strings.
25 swapcase() Returns the string with case >>> str1.swapcase()
changes 'hello'
>>> str1
'HELLO'
26 title() Returns "titlecased" version >>> str1
of string, that is, all words 'HELLO'
begin with uppercase and >>> str1.title()
the rest are lowercase. 'Hello'
27 partition(sep) The function partitions the >>> str3.partition("l")
strings at the first ('He', 'l', 'lo Class')
occurrence of separator,
and returns the strings
partition in three parts i.e.
before the separator, the
separator itself, and the
part after the separator. If
the separator is not found,
returns the string itself,
followed by
two empty strings
28 upper() Returns the exact copy of >>> str2
the string with all letters in 'class'
uppercase. >>> str2.upper()
'CLASS'
29 isdecimal() Returns true if a unicode >>> str1.isdecimal()
string contains only decimal False
characters and false
otherwise.
Let us take example of some function of string:
The output of these function are as follows:
Summery
 String is group of characters. It can be declared by single and double quotes.
 Strings can be accessed partially by slicing method and fully by printing the string
variable by name.
 String has may function as used in list tuple and dictionary like length, concatenate ,
repeat and slicing.
 But it has some more other useful function too like upeer(),lower(),title() max(),min()
and join().
 String has some comparative functions like isupper(), islower(), istitle(),isalpha() a,d
co on to compare string is in that particular form or not.
Multiple Choice Questions
Q.1 >>>"a"+"bc"
a) a
b) bc
c) bca
d) abc
Answer: d
Explanation: + operator is concatenation operator.
Q.2 What is the output when following statement is executed ?
>>>"abcd"[2:]
a) a
b) ab
c) cd
d) dc
Answer: c
Explanation: Slice operation is performed on string.
Q.3 The output of executing string.ascii_letters can also be achieved by:
a) string.ascii_lowercase_string.digits
b) string.ascii_lowercase+string.ascii_upercase
c) string.letters
d) string.lowercase_string.upercase
Answer b
Q.4 What is the output when following code is executed ?
>>> str1 = 'hello'
>>> str2 = ','
>>> str3 = 'world'
>>> str1[-1:]
a) olleh
b) hello
c) h
d) o
Answer: d
Explanation: -1 corresponds to the last index.
Q.5 What arithmetic operators cannot be used with strings ?
a) +
b) *
c) –
d) All of the mentioned
Answer: c
Explanation: + is used to concatenate and * is used to multiply strings.
Q.6 What is the output when following code is executed ?
>>>print r"\nhello"
The output is
a) a new line and hello
b) \nhello
c) the letter r and then hello
d) error
Answer: b
Explanation: When prefixed with the letter ‘r’ or ‘R’ a string literal becomes a raw string and
the escape sequences such as \n are not converted.
Q.7 What is the output when following statement is executed ?
>>>print('new' 'line')
a) Error
b) Output equivalent to print ‘new\nline’
c) newline
d) new line
Answer: c
Explanation: String literals seperated by white space are allowed. They are concatenated
Q.8 What is the output when following code is executed ?
>>>str1="helloworld"
>>>str1[::-1]
a) dlrowolleh
b) hello
c) world
d) helloworld
Answer: a
Explanation: Execute in shell to verify.
Q.9 What is the output of the following code ?
>>>example = "snow world"
>>>print("%s" % example[4:7])
a) wo
b) world
c) sn
d) rl
Answer: a
Q.10 What is the output of the following code ?
>>>example = "snow world"
>>>example[3] = 's'
>>>print example
a) snow
b) snow world
c) Error
d) snos world
Answer: c
Explanation: Strings cannot be modified.
Descriptive Questions
Q.1 How will you check in a string that all characters are numeric?
Q.2 How will you merge elements in a sequence?
Q.3 What is string formatting operator? How it works.
Q. 4 How can we encode any string? Provide all the encoding related method.
Q. 5 What is slicing in string and how it works? Provide different options in slicing.
Laboratory Exercise Questions
Q.1 Write a program to find whether the given string is palindrome or not with and without
building functions.
Q.2 Write a program to count the number of characters in a string without using len()
function.
Q.3 Write a program to remove the nth index character from a nonempty string.
Q.4 Write a program to count the occurrences of each word in a given sentence.
Q.5 Write a program to swap two strings.
Q.6 Write a program to count the number of characters (character frequency) in a string.
Q.7 Write a program that takes a list of words and returns the length of the longest one.
Q.8 Write a program to remove the characters which have odd index values of a given string.
Q.9 Write a program that takes input from the user and displays that input back in upper and
lower cases.
Q.10 Write a program to sort a string lexicographically.

You might also like