0% found this document useful (0 votes)
2 views56 pages

String

Chapter 8 provides a comprehensive overview of strings in Python, detailing their definition, internal representation, and various operations such as indexing, slicing, and formatting. It emphasizes that strings are immutable and introduces string operators and built-in methods for manipulation. The chapter concludes with examples and exercises to reinforce understanding of string concepts.

Uploaded by

munish
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)
2 views56 pages

String

Chapter 8 provides a comprehensive overview of strings in Python, detailing their definition, internal representation, and various operations such as indexing, slicing, and formatting. It emphasizes that strings are immutable and introduces string operators and built-in methods for manipulation. The chapter concludes with examples and exercises to reinforce understanding of string concepts.

Uploaded by

munish
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

CHAPTER

8 String

Contents
8.1 Introduction
8.2 String: An Overview
8.3 Internal Representation of String
8.4 Accessing Characters in String
8.4.1 Using Indexing
8.4.2 Using Slicing
8.4.3 Using Stride with Slicing
8.5 String Mutation: Immutable Strings
8.6 String Operators
8.7 String Traversal and Accumulation
8.8 String Formatting
8.8.1 Escape Sequence
8.8.2 Formatting Operator
8.8.3 Method Format()
8.9 Built-in String Methods
8.10 Solved Questions with Explanation
8.11 Programming Examples
Summary
Keywords
Programming Language Keywords
Assessment
Answers

8.1 Introduction
In the earlier chapters, we have discussed the simple data types like int and
float that cannot be further broken down. Python also has compound data
type. The compound data type can be further broken down into smaller pieces.
One kind of compound data type is a sequence data type. Sequence is a generic
term for an ordered collection of objects. Multiple values can be organized and
stored efficiently using sequence data type. There are several types of sequences.
String, list and tuple are important sequence data type. String is a popular data
type and was introduced in the earlier chapters.
String is defined using data type str. String is made up of smaller strings
that are further made up of characters. We have seen defining of string literal
in single, double and triple quotes. We also noted that the characters in a string
can be digits, alphabets, symbols and whitespace characters including null.
String is an immutable sequence. String can be manipulated and different
operations can be performed on string. In this chapter, we discuss the string
data type in detail.
Learning Outcomes of this chapter
After completion of the chapter, the learner will be able to:
• Formulate problems having string manipulation
• Use strings in programs
• Use string operators for performing string operations
• Identify different types of string formatting
• Develop programs based on the concepts discussed.

8.2 String: An Overview


• A string is a sequence of characters.
• The characters can be digits, alphabets, symbols and whitespace characters
such as newline (‘\n’) and, tab (‘\t’) including blank space.
• A string can be empty. An empty string has zero characters.
• In Python, the str data type represents string.
• A str literal is a sequence of characters enclosed in quotes.
• The quotes can be single quotes (‘), double quotes (“) or triple quotes (”””).
The same type of quote must start and end a string (Figure 8.1).
• The triple quotes are used to span the string across multiple lines.

Figure 8.1 String literal in Python

8.3 Internal Representation of String


• The characters seen on the screen are stored and manipulated internally in
the computer as numbers – a combination of 0s and 1s.
• Encoding is the conversion of a character to a number.
• Decoding is the conversion of a number to a character.
• ASCII and Unicode are popular encodings that are used.
• Unicode
o Brings uniformity in coding and includes every character in all
languages.
o Every character has a unique number irrespective of platform, program
and language.
• Code points are numerical values that make up code space.
o ASCII-7 has 128 code points from 0(16) to 7F(16)
o ASCII-8 has 256 code points from 0(16) to FF(16)
o Unicode has 1,114,112 code points from 0(16) to 10FFFF(16),
divided into 17 planes each with 65536 code points. Thus, total is 17 *
65536 = 1,114,112
• Unicode string is a sequence of code points. Encoding involves rules for
translating Unicode string to a set of bytes (values 0 to 255) in memory.
• In Python, string is a sequence of Unicode characters.
• String or text has properties like, split, slice, join and add.
8.4 Accessing Characters in String
We know that string is a sequence of characters. We shall now understand
enumeration of a string.
• Let us take a string ‘Love Yourself ’.

The characters in the string are enumerated as follows:


o Left to Right, the characters of a string are enumerated starting from 0.
o Right to Left, the characters are enumerated starting from −1.
o Enumeration corresponds to the index. From left to right, the index is
0, 1, 2 … and from right to left, index is −1, −2, −3, …
o Index starts from 0, so the maximum index of string is 1 less than its
length.

8.4.1 Using Indexing


• To access characters in a string, indexing is used.
• Indexing allows to retrieve a part of the string.
• Any character of a string can be accessed by writing the string name
followed by index in square brackets.
• Indexing can be done in two ways – Positive indexing and Negative
indexing.
• Positive Indexing: It starts from the left side of the string starting from 0.
For example, if a = “LOVE YOURSELF”, a[2] gives the letter “V”.

• Negative Indexing: It starts from the right side of the string starting from
−1. For example, if a = “LOVE YOURSELF”, a[−2] gives the letter “L”.
8.4.2 Using Slicing
• Slicing Operator: The slicing operator is a square bracket []. It allows
creation of a substring from a string. The syntax of slicing operator is
string[start:end]
start - index from where the slice starts
end - index where slice ends (excluding end index)
The substring from index start to end−1 is returned. Index start and end are
optional. If omitted, the default value of start is 0 and end is the last
index of the string.
• Range Indexing: It allows specifying a range of indexes, to get substrings.
All characters starting from index start to end−1 are obtained. For example,
if a = “LOVE YOURSELF”, a[5:8] gives “YOU”.

Example 8.1: (a) Using range indexing (b) Output

• When specifying range indexing, the start or end index can be omitted.
o If start index is omitted, the substring from beginning of the string till
end−1 is returned.
o If end index is omitted, the substring from the start index till the end
of the string is returned.
• Index can also be negative. The indexing starts from right to left in
negative indexing.
o start index is lower than end index. For example, (−5, −2) start is -5
lower than end −2)
Example 8.2: (a) Using negative index (b) Output

• The index must be an integer, otherwise it will result in TypeError.

Output

• The index must be in range, otherwise it will result in IndexError.


• When we use range to access strings, the following may be noted:
o If index range start is greater than end, no output is displayed.
o If index range start or end is more than the size of the string, there is no
error.
o If index start or end is more than the size of the string, and
positive/negative index is used but range is not used, then IndexError
arises.
Example 8.3: (a) String indexing (b) Output

8.4.3 Using Stride with Slicing


• Stride is the third parameter that can be specified, in addition to start
and end index.
• The syntax is
String[start: end: stride]
• Stride specifies the number of characters to move forward after each
character retrieval. So, the characters retrieved are: start, start+stride,
start+stride+stride, --- end−1. For example,
S = “LOVE YOURSELF”
S[1:10:2] will return OEYUS
• The default value of stride is 1. When we do not mention stride, all
characters between start and end are retrieved.
s[2:4] and s[2:4:1] retrieve same substring from a string s.
• A negative stride will retrieve string from start to end backwards. So, the
start index must be greater than end index, otherwise nothing is
returned.
Example 8.4: (a) Using negative stride (b) Output

8.5 String Mutation: Immutable Strings


• Strings are immutable. This means that when a string has been assigned to
a variable, its value cannot be changed. We explain this as follows:
o Let us assign s = “Anita”. Then an object “Anita” is created and variable
s is assigned the object.
o When we assign s = “Python”, a new object (with a different object-id
than the earlier one) is created and the variable s is assigned the object.
o We see that when we change a string, the changes do not happen in the
same object-id; a new object is created.
o So, strings cannot be updated in place. They are immutable.

• In the code below, we see that when we print s[2], there is no error and it
prints “i”. But when we try to change the value of s[2], an error is thrown.
This because we cannot change a string. Characters of a string cannot be
changed or deleted.

• A string can be deleted. For this, the del command is used.


del s
deletes the string s.

8.6 String Operators


Several operations can be performed on strings. Table 8.1 shows the operations
that can be performed on strings.

Table 8.1 String operations


Task Description Operator Example Output
Concatenation Joins two or +
more strings
into one
string
Writes
strings
together
Joins strings ()
in different
lines
Repetition Repeating a *
string for a
number of
times
Slice Gives []
character
from the
given index

Range Slice Gives [: ]


characters
from the
given range
Task Description Operator Example Output
Membership Returns true in
if character
exists in the
given string
Returns true not in
if character
is not in the
given string
Comparison Compares >
strings using <
ASCII values <=
in >=
lexicographic !=
order ==
Ord() Returns
ACSII code of
character
Chr() Returns
character for
ASCII code
Example 8.5: (a) Using string operations (b) Output
8.7 String Traversal and Accumulation
Traversal of string means accessing each element in the string, one by one.
Traversal can be done using a loop – for loop or while loop. Here we show
an example to traverse a string using while loop and for loop.
Output
8.8 String Formatting
The string printed in the output can also be formatted. There are different ways
of formatting the string, as follows:
• Using Escape characters
• Using percentage sign (%)
• Using Format method

8.8.1 Escape Sequence


The backslash “\” is a special character in Python that is called escape character.
It is used for different purposes as follows:
• Representing whitespace characters There are certain whitespace characters,
like tab, newline and carriage return, that are required to be printed. The
escape character is followed by the character to be used. Table 8.2 shows
the escape characters and their description.

Table 8.2 Escape characters in Python


Backslash notation Description
\a Bell or alert
\b Backspace
\e Escape
\f Form feed
\n Newline
\r Carriage return
\s Space
\t Horizontal tab
\v Vertical tab
\x Character x
\0nn Character with octal value (n is from 0 to
7)
\xnn Character with hexadecimal value (n is
from 0-9, A-F)

Output

• Representing a special character as ordinary character There are certain


characters that cannot be printed directly, like single quotes and double
quotes. This is because, they already form part of the string syntax to
represent a string. So, the escape sequence is used to print such characters.
Such characters are prefixed with backslash “\”.
Output
So, when we use escape sequence with double quotes, the output is displayed
as follows:

Output

To print a backslash in the output, a double backslash is used.

Output

8.8.2 Formatting Operator


Python has a built-in operator % that is used for formatting. The use of % is a
C-style formatting for strings in Python. The % with a character is used for
formatting. It is defined as a placeholder for values to be inserted in the string.
The values to which format is applied, is defined as a tuple at the end of the
string. The use of formatting operator is an old-style of formatting, though it is
still used widely.
Let us see an example.

Output

Output
Table 8.3 shows the list of all symbols that can be used with % for string
formatting.

Table 8.3 Symbols used with formatting operator


Format Symbol Conversion
%c character
%s string
%i or %d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase ‘e’)
%E exponential notation (with UPPERcase ‘E’)
%f floating point real number
%g shorter of %f and %e
%G shorter of %f and %E

Also, there are some more symbols as listed in Table 8.4.

Table 8.4 More symbols with formatting operator


Symbol Functionality
* argument specifies width or precision
- left justification
+ display sign
<sp> leave a blank space before a positive number
# add octal leading zero ( ‘0’) or hexadecimal leading
‘0x’ or ‘0X’, depending on whether ‘x’ or ‘X’ were
used.
0 pad from left with zeroes (instead of spaces)
% ‘%%’ gives a single literal ‘%’
(var) mapping variable (dictionary arguments)
m.n. m is minimum total width and n is number of digits
to display after decimal point

Some examples of formatting are as follows:


Example 8.6: (a) Using string formatting operators (b) Output

Example 8.7: (a) Print table of 2 and display using string formatting (b)
Output
8.8.3 Method Format()
String formatting using format() method is a new style of formatting.
Format() is a method of class string in Python. The syntax of the
format() method is as follows:
[Link](p0, p1, p2, …, k0=v0, k1=v1, …)
• Template is a string that contains fields to be replaced, or embedded in
text. The fields to be replaced are written as curly braces{}. The braces act as
placeholders or replacement fields that get replaced.
• The syntax contains two kind of arguments – Positional arguments and
Keyword arguments.
o Positional arguments are p0, p1, p2, …. They can be accessed with
index of argument inside curly braces {index}.
o Keyword arguments are k0, k1, … with values v0, v1,... They are of
type key = value. They can be accessed with key of argument inside
curly braces {key}.
• Anything that is not in braces is printed as it is.
Let us understand formatting using an example.
The points to be noted are:
• The string has two parts – template (before dot) and format parts (after
dot).
• Template defines the string to be printed. Curly braces are put at positions
where the fields are to be formatted. Format has the value of fields that will
replace curly brackets at runtime.
• The values defined in format have an index. The first value is index 0,
second is index 1, and so on.
• In format, if positional arguments are used in the order they are defined,
‘{0}{1}{2}’, then in template, the index in braces can be omitted. Empty
braces are a default option. The format() values replace the template
braces, in order. The first value replaces the first brace, the second value
replaces the second brace, and so on.

The output is:

• In format, if positional arguments are to be accessed in a different order,


say, ‘{2}{0}{1}’ in the string to be printed, the braces can mention index,
i.e., the position order in which values of format will replace the braces in
the string. For example,

The output is:

• The keyword arguments are of the form key=value. In template, the braces
in string mention the key. In format, the value corresponding to key
replaces the braces in string. For example,

The output is:

• To print a brace character in the output, a double brace is used, {{ and }}.
• Optional Format Specification: The index in curly braces can be followed
by a colon and format string. The format string defines the formatting for
the field. Tables 8.5 and 8.6 specify some commonly used formatting
specifications.
• The field width is always the size of data to be printed, so alignment has no
meaning. To use alignment, minimum field width is required to be
defined.
Table 8.5 Optional format specifications
Option Meaning
‘<’ Field will be left-aligned. Strings are, by default, left-aligned.
‘>’ Field will be right-aligned. Numbers are, by default, right-
aligned.
‘^’ Field will be centred.
‘,’ Comma for ‘thousand’ separator is used in numeric.
‘0’ Field width will be preceded with 0. Sign-aware zero padding.
Only for numeric type of data.
‘=’ Forces padding to be placed after sign but before digits, like,
+00089. Only for numeric type of data.

Table 8.6 Number formatting types (optional)


Type Meaning
d Decimal integer
c Corresponding Unicode character
b Binary format
o Octal format
x Hexadecimal format (lower case)
X Hexadecimal format (upper case)
e Exponential notation. (lowercase e)
E Exponential notation (uppercase E)
f Displays fixed point number (Default: 6)
F Same as ‘f ’. Except displays ‘inf ’ as ‘INF’ and ‘nan’ as ‘NAN’
g General format. Rounds number to p significant digits.
(Default precision: 6)
G Same as ‘g’. Except switches to ‘E’ if the number is large.
% Percentage. Multiplies by 100 and puts % at the end.

Some examples of formatting are as follows:


Example 8.8: (a) Using string formatting types (b) Output

Example 8.9: (a) Using string alignment format (b) Output


Example 8.10: (a) Using string alignment with spacing (b) Output
8.9 Built-in String Methods
Python supports several built-in methods that can be used with strings. The
syntax to use the methods is:
[Link]()
String Methods and the String Module: The string methods in Python 3.x have
replaced the earlier String module. Though Python 3.X supports the string
module for backward compatibility, you should now use the String Methods
and not the String Module.
Table 8.7 lists the built-in string methods.

Table 8.7 Built-in string methods


S. No Method Name Syntax and Description
1 capitalize(...) [Link]() →str
Makes the first character upper case
and rest lower case.
2 casefold(...) [Link]()→ str
Returns version of S suitable for
caseless comparisons.
3 center(...) [Link](width[, fillchar]) → str
S centered in string of length width.
Padding is done using fill character
(default is space).
4 count(...) [Link](sub[, start[, end]]) → int
Returns number of non-overlapping
occurrences of substring sub in string
S[start:end].
5 endswith(...) [Link](suffix[, start[, end]]) →
bool
S. No Method Name Syntax and Description
Returns True if S ends with specified
suffix, False otherwise. With optional
start, tests S beginning at start. With
optional end, stops comparing S at
end. suffix can also be a tuple of
strings to try.
6 expandtabs(...) [Link](tabsize=8) → str
Returns copy of S where all tab
characters are expanded using spaces.
If tabsize 8is not given, a tab size of 8
characters is assumed.
7 find(...) [Link](sub[, start[, end]]) → int
Returns lowest index in S where
substring sub is found, such that sub is
contained within S[start:end]. Returns
−1 on failure.
8 format(...) [Link](*args, **kwargs) → str
Returns formatted version of S, using
substitutions from args and kwargs.
The substitutions are identified by {}.
9 format_map(..) S.format_map(mapping) → str
Returns formatted version of S, using
substitutions from mapping. The
substitutions are identified by {}.
10 index(...) [Link](sub[, start[, end]]) → int
It is like [Link]() but raises ValueError
when the substring is not found.
11 isalnum(...) [Link]() → bool
Returns True if all characters in S are
alphanumeric and there is at least one
S. No Method Name Syntax and Description
character in S, False otherwise.
12 isalpha(...) [Link]() → bool
Returns True if all characters in S are
alphabetic and there is at least one
character in S, False otherwise.
13 isdecimal(...) [Link]() → bool
Returns True if there are only decimal
characters in S, False otherwise.
14 isdigit(...) [Link]() → bool
Returns True if all characters in S are
digits and there is at least one
character in S, False otherwise.
15 isidentifier(...) [Link]() → bool
Returns True if S is a valid identifier
according to the language definition.
Uses [Link]() to test for
reserved identifiers such as “def ” and
“class”.
16 islower(...) [Link]()→ bool
Returns True if all cased characters in
S are lowercase and there is at least one
cased character in S, False otherwise.
17 isnumeric(...) [Link]() → bool
Returns True if there are only numeric
characters in S, False otherwise.
18 isprintable(...) [Link]() → bool
Returns True if all characters in S are
considered printable in repr() or S is
empty, False otherwise.
S. No Method Name Syntax and Description
19 isspace(...) [Link]() → bool
Returns True if all characters in S are
whitespace
and there is at least one character in S,
False otherwise.
20 istitle(...) [Link]() → bool
Returns True if S is a title cased string
and there is at least one character in S,
i.e., uppercase and title-case characters
may only follow uncased characters
and lowercase characters only cased
ones. Returns False otherwise.
21 isupper(...) [Link]()→ bool
Returns True if all cased characters in
S are uppercase and there is at least
one cased character in S, False
otherwise.
22 join(...) [Link](iterable) → str
Returns a string which is
concatenation of strings in iterable.
The separator between elements is S.
23 ljust(...) [Link](width[, fillchar]) → str
Returns S left-justified in a Unicode
string of length width. Padding is done
using the specified fill character
(default is a space).
24 lower(...) [Link]() → str
Returns a copy of string S converted to
lowercase.
S. No Method Name Syntax and Description
25 lstrip(...) [Link]([chars]) → str
Returns a copy of string S with leading
whitespace removed. If chars is given
and not None, it removes characters in
chars instead.
26 partition(...) [Link](sep) → (head, sep, tail)
Searches for separator sep in S, and
returns the part before it, the separator
itself, and the part after it. If separator
is not found, it returns S and two
empty strings.
27 replace(...) [Link](old, new[, count]) → str
Return a copy of S with all
occurrences of substring, old replaced
by new. If optional argument count is
given, only first count occurrences are
replaced.
28 rfind(...) [Link](sub[, start[, end]]) → int
Returns the highest index in S where
substring sub is found, such that sub is
contained within S[start:end].
Optional arguments start and end are
interpreted as in slice notation.
Returns −1 on failure.
29 rindex(...) [Link](sub[, start[, end]]) → int
It is like [Link]() but raisees
ValueError when substring is not
found.
30 rjust(...) [Link](width[, fillchar]) → str
S. No Method Name Syntax and Description
Returns S right-justified in a string of
length width. Padding is done using
fill character (default is space)
31 rpartition(...) [Link](sep) → (head, sep, tail)
Searches for separator sep in S, starting
at end of S, and returns the part before
it, the separator itself, and the part
after it. If separator is not found, it
returns two empty strings and S.
32 rsplit(...) [Link](sep=None, maxsplit=-1) → list
of strings
Returns list of words in S, using sep as
delimiter string, starting at the end of
string and working to front. If
maxsplit is given, at most maxsplit
splits are done. If sep is not specified,
any whitespace string is a separator.
33 rstrip(...) [Link]([chars]) → str
Returns a copy of string S with trailing
whitespace removed. If chars is given
and not None, it removes characters in
chars instead.
34 split(...) [Link](sep=None, maxsplit=-1) → list
of strings
Returns a list of words in S, using sep
as delimiter string. If maxsplit is given,
at most maxsplit splits are done. If sep
is not specified or is None, any
whitespace string is a separator and
S. No Method Name Syntax and Description
empty strings are removed from the
result.
35 splitlines(...) [Link]([keepends]) → list of
strings
Returns a list of lines in S, breaking at
line boundaries. Line breaks are not
included in resulting list unless
keepends is given and true.
36 startswith(...) [Link](prefix[, start[, end]]) →
bool
Returns True if S starts with the
specified prefix, False otherwise. With
optional start, it tests S beginning at
that position. With optional end, it
stops comparing S at that position
prefix. It can also be a tuple of strings
to try.
37 strip(...) [Link]([chars]) → str
Returns a copy of the string S with
leading and trailing whitespace
removed. If chars is given and not
None, it removes characters in chars
instead.
38 swapcase(...) [Link]()→ str
In S, it swaps uppercase characters to
lowercase and vice-versa.
39 title(...) [Link]()→ str
Returns a title-cased version of S, i.e.,
words start with title case characters,
S. No Method Name Syntax and Description
all remaining cased characters have
lowercase.
40 upper(...) [Link]()→ str
Returns a copy of S converted to
uppercase.
41 zfill(...) [Link](width) → str
Pads a numeric string S with zeros on
left, to fill a field of specified width. S
is never truncated.

Some examples are as follows:


Example 8.11: (a) Using string method (b) Output
Example 8.12: (a) Using string method (b) Output
8.10 Solved Questions with Explanation
1) Find the output:

Output

Explanation: It counts the number of letter “o” in the


string.
2) Find the output:

Output

Explanation: The second print replaces all occurrences


of the substring in the string. The third print replaces only
one occurrence of the substring in the string.
3) Find the output:

Output

Explanation: The first print splits x. The delimiter is


space. The second split splits into 3(0,1,2). The third prints
into 4. The fourth print splits starting from right side.
4) Find the output:

Output
Explanation: It prints the first and last letter in uppercase. The rest of the
letters are retained in lower case.
5) Find the output:

Output

Explanation: It prints the number of total characetrs, space characters and


non-space characters.

8.11 Programming Examples


Program 8.1: WAP to remove the nth letter from the string.

Output
Program 8.2: WAP to find number of occurrences of uppercase and lowercase
letters in a string.

Output

Program 8.3: WAP to find the length of each word in a string.

Output
Program 8.4: WAP to swap the first and last character of a string.

Output

Program 8.5: WAP to count the number of consonants and vowels in a string.
Output

Program 8.6: Given two strings. WAP that efficiently finds the longest
common subsequence
A longest common subsequence (LCS) is the longest subsequence of
elements in the same order which is common in all given input sequences.
Let us take two strings (1) “ABCDEFG” and (2) “ACEFGHI”
The longest subsequence present in both strings is - ACEFG
Output

Summary
• A string is a sequence of digits, alphabets, symbols and whitespace
characters.
• Conversion of a character to a number is called encoding.
• Conversion of number to a character is called decoding.
• String is a sequence of Unicode characters.
• Indexing allows accessing characters of the string.
• Positive indexing is accessing of string from left to right with index 0, 1, …
• Negative indexing is accessing of string from right to left with index −1,
−2, …
• To create a substring from a string, slicing is used.
• Slicing allows specifying a range of index for accessing characters from a
string.
• Stride is used to skip characters in between the slice.
• Strings are immutable, i.e., once created, a string cannot be updated in
place. Any update of string creates a new string.
• String concatenation, repetition, membership and comparison are some of
the operations that can be performed on strings.
• The for loop and while loop are used to traverse the elements of a
string.
• A string can be formatted using escape character, using format operator
(%) and using format method.
• The format method uses positional arguments and keyword arguments for
formatting.
• There are several built-in string methods that can be used with strings.

Keywords
String
Single quotes
Double quotes
Triple quotes
Encoding
Decoding
ASCII
Unicode
Code point
String enumeration
Index
Positive indexing
Negative indexing
Slicing
Slicing operator []
Range indexing
TypeError
IndexError
Stride
Negative stride
String update
Immutable strings
Delete string ()
String operator
String concatenation (+)
Repetition
Range Slice [:]
Membership (in)
Membership (not in)
String comparison
String Traversal
String formatting
Escape characters (\)
Formatting operator (%)
Positional arguments
Keyword arguments
[Link]()

Programming Language Keywords


[]
Chr()
Ord()
Del
not in
format
in
Str

Assessment
A.1 Bloom Level: Knowledge/Remember

Review Questions
1. Define – String, Encoding, Decoding.
2. In Python, which encoding is used for string?
3. List three sequence data types.
4. List one mutable sequence data type.
5. List two immutable sequence data types.
6. Can a string be empty?
7. Match the following:
Column A Column B
1 [] a Concatenation
2 [:] b Indexing
3 [::] c Slice Stride
4+ d Membership
5* e Escape character
6 In f Repetition
7\ g Range Slice
8. List three ways of formatting a string.
9. List the escape sequence used for horizontal tab.
10. Name three built-in methods for strings and explain
their function.

Fill in the Blanks


1. Empty string has ____ characters.
2. Triple quotes are used to span string across ____ lines.
3. ______ and ______ are popular encodings.
4. Each plane in Unicode has _____ code points.
5. The leftmost index of a string, starting from left is
_____.
6. The rightmost index of the string, starting from right
is ___.
7. The minimum positive index is _____.
8. The indexing in a string can be _____ indexing and
______ indexing.
9. ______ operator allows creating substring from a
string.
10. Using _______ returns ASCII code of character.
11. Using ______ returns character for the ASCII code.
12. ______ is used for printing newline in output.
13. ______ is used for printing horizontal ____ in output.
14. Encoding is conversion from _________ to __________.
15. Decoding is conversion from __________ to ___________.
16. The number of code points in ASCII-8 are
_____________.
17. The number of code points in ASCII-7 are
_____________.
18. The number of code points in a plane for Unicode are
_____________.
19. The positive indexing starts from ________ to _________.
20. The negative indexing starts from ________ to _________.

State True/False
1. A string cannot be empty.
2. Encoding is conversion of number to character.
3. String can be indexed both from left to right and from
right to left.
4. Negative index starts from left to right.
5. [:] is a slice operator.
6. The index to access character in a string must be an
integer.
7. * operator is used for concatenation.
8. ASCII of ‘A’ is 97.
9. Backslash is the escape character.
10. % is formatting operator.
11. < is used to right align in format method.

A.2 Bloom Level: Comprehend/Understand

Review Questions
1. What is the purpose of using triple quotes in string?
2. Explain the difference in Unicode and ASCII encoding
for internal representation of string.
3. Explain the meaning of “Strings are immutable”.
4. What is the purpose of del command?
5. What is the purpose of slicing? Explain with an
example.
6. If we want to update a string, is it possible? Explain
the reason in support of your answer.
7. Two strings are compared to get the larger string.
What is the basis on which the comparison happens?
8. What is the purpose of membership operator? Explain
with an example.

A.3 Bloom Level: Application/Apply

Review Question
1. Find errors, and correct the code:
(a)
(b)
(c)

Fill in the Blanks


1. The slice s[3:6] will retrieve characters in string from
index ____ to ______.
2. The start and end index to access ‘ea’ from ‘beauty’ is
___ and ____.
3. The output of s[0:20] on s = “Change the World” is
______.
4. The output of s[−20: −1] on s = “Change the World” is
______.
5. The output of “Good”*3 is ______.
6. The output of “Good” + “Morning” is _____.
7. The output of “Good” “Morning” is ______.
8. The output of “d” in “Good” is ____________.
9. The output of “e” not in “Good” is ______.
10. Print(“{:>10}.format(“Python”)) will ______ align the
word Python.
11. The output of “GOOD” > “good” is ____________.

Match the Following


a = “Everything is Energy”
Match the print statements with their output.
Print Statement Output
(i) print(a[3]) a) ing is Energy
(ii) print(a[0:1]) b) Eeyhn
(iii) print(a[0:7]) c) erything is Energ
(iv) print(a[7:]) d) E
(v) print(a[-5:]) e) r
(vi) print(a[:10:2]) f ) nergy
(vii) print( a[::]) g) Everyth
(viii) print(a[2:-1]) h) Everything is Energy

Multiple Choice Questions (MCQ)


1. Identify the invalid string literal.
(i) “ABC”
(ii) “12AB”
(iii) ABC
(iv
) “12_AB”
2. The index of ‘e’ in string ‘grateful’ is ______.
(i) 4
(ii) 5
(iii) 6
(iv
) −5
3. A[3] in string A = “Be Strong” is ______.
(i) S
(ii) t
(iii) Blank
(iv
) e
4. A[−3] in string A = “Be Strong” is ______.
(i) n
(ii) r
(iii) o
(iv
) Blank
Answer 5–8 for the string
s = “Change the World”
5. The output of s[2:5] is ______.
(i) ange
(ii) ang
(iii) hang
(iv
) han
6. The output of s[−3] is ______.
(i) o
(ii) r
(iii) l
(iv
) g
7. The output of s[0:10:3] is ______.
(i) Cn e
(ii) Cagte
(iii) Cn t
(iv
) None
8. The output of s[2:] on string “Beauty” is ______.
(i) a
(ii) auty
(iii) aut
(iv
) error
9. For s = “Change the World”, which of the following
will result in an error?
(i) s[0:20]
(ii) s[-20:0]
(iii) s[-20]
(iv
) All
10. Identify the correct answer.
S[0:20] when applied on string s = “Beautiful Heart: will give:
(i) Beautiful Heart
(ii) Syntax error
(iii) Index error
(iv
) Type error
A.4 Bloom Level: Analyze
1. Explain the difference between positive and negative
indexing.
2. What is the difference between positional arguments
and keyword argument in method format()?
3. When using strings, what is the difference between
TypeError and IndexError?
4. Differentiate between s[3:6] and s[3:6:1] when applied
on string s = “Beautiful World”
5. Differentiate between the method capitalize() and
upper(). Explain with example.
6. Differentiate and analyze the output with justification.
(i)
(a)
(b)
(c)
(ii)
(a)
(b)
(c)
(iii)
(a)
(b)
(c)
7. Let s = “Be kind to animals.” Write Python statements
to get:
s[0], s[0:1], s[0:7], s[:7], s[-7:], s[:-7], s[:], s[8:3], s[8:-1], s[-10:-3]
8. In the string s = “Be nice to yourself” give the output
for the following:
S[0:4:2], s[10:4:-1], s[4:10:-1], s[2::3], s[2::-3], s[:10:3], s[2::1], s[::]

A.5 Bloom Level: Evaluate


1. An output is given and print statements for getting
that output is also shown.
Output

Code

Evaluate the following outputs and write the print statememts for the
following.

2. For the following lambda functions, (i) identify the


task performed, (ii) find the output, (iii) evaluate the
output for inputs.

(a)

What will be the output if a user enters the string: APPRECIATE?


(b)

(c)
What will be the output if a user enters the string: Save the Environment?

(d)

What will be the output if a user enters string: Greet Everyone?


The character to be removed is “e.”

(e)

(i) What will be the output if a user enters the


string: Greet Everyone?
(ii) What will be the output if a user enters the
string: abracadabra?
(iii) What will be the output if a user enters the
string: Racecar?
(iv
) What will be the output if a user enters the
string: Do geese see God?
If answer is No in (iii), what change in the code should be done to get
Yes.
If answer is No in (iv), what change in the code should be done to get
Yes.

A.6 Bloom Level: Create/Synthesize

Programming Assignment
Apply formatting wherever possible.
1. Specify a Python statement to get the character “a”
from the string “Change”.
2. Write a statement to print the characters of the string
“Grateful”.
3. WAP to check if a substring is present in a given
string.
4. WAP to print words having even length in a string.
5. WAP to print words having odd length in a string.
6. WAP to print words having length greater than or
equal to n in a string. Accept n from user.
7. WAP with functions defined for problems (4), (5), (6).
Define a menu to accept user choice.
8. WAP to accept two strings. Find how many characters
are matching in the two strings.
9. WAP to remove all duplicate characters in a given
string.
10. WAP to find the sum of the ASCII number of each
character in a string.
11. WAP to count the number of words in the string and
tell whether they are odd or even.
12. WAP to reverse a string.
13. WAP to count occurrences of each word in a string.

Answers
A.1 Bloom Level: Knowledge/Remember

Review Questions
6. (1) b (2) g (3) c (4) a (5) f (6) d (7) e
Fill in the Blanks
1. zero
2. multiple
3. ASCII, Unicode
4. 65536
5. zero
6. −1
7. zero
8. positive, negative
9. Slice
10. Ord()
11. Chr()
12. \n
13. \t
14. character, number
15. number, character
16. 256
17. 128
18. 65536
19. left, right
20. right, left

True/False
1. False
2. False
3. True
4. False
5. True
6. True
7. False
8. False
9. True
10. True
11. False
12.

A.3 Bloom Level: Apply

Review Question
1. (a)
1. (b)
1. (c)
1. False
2. True
3. False
4.
5.
6.
7.
8.

Fill in the Blanks


1. 3, 5
2. 1,3
3. Change the World
4. Change the Worl
5. GoodGoodGood
6. GoodMorning
7. Good Morning
8. True
9. True
10. right
11. False
12.

Match the Following


1. (i)– (e), (ii)– (d), (iii)– (g), (iv)– (a), (v)– (f), (vi)– (b), (vii)–
(h), (viii)– (c)

Multiple Choice Questions (MCQ)


1. (iii)
2. (i)
3. (i)
4. (iii)
5. (ii)
6. (ii)
7. (i)
8. (ii)
9. (iii)
10. (ii)

A.4 Bloom Level: Analyze


5. (i) (a) 4
(b) 4
(c) 4
5. (ii) (a) 17
(b) 17
(c) -1
5. (iii) (a) 21
(b) 21
(c)

A.5 Bloom Level: Evaluate

1.

2. (a) Prints the first five letters of the input string.


(b) GoodMorning
(c)

(d)

(e) (iii), (iv)

You might also like