You are on page 1of 30

CHAPTER Five: Strings in Python

Objectives of this chapter: To provide the learner with detailed concepts on


 Strings
 How they are dealt with in reference to
1. Concatenation and repetition
2. Indexing and Slicing
3. String methods
4. String formatting
5. Problem solving

5.1 Introduction.
A string is any text enclosed within quotation marks. The quotation signs may either be
single or double or even triple. The triple quotation signs are particularly required for
multiline strings. To speak at micro level, a string can be defined as a sequence of Unicode
characters enclosed within quotes. Python does not recognize character data type; here even
a character or a space is a data of type string. It is also called a str object. The concept of an
object will be discussed in a later section. In the following sections we will elaborate the
concept of strings used in Python and different defined methods that have been defined to
apply on strings.

1.2 How to create and use a string.


Let us create a string by using the macro level definition given in the preceding section
and then get it printed as illustrated in the figure below:
>>> Sting='I love Python'
>>> print(Sting)
I love Python
>>> Sting="I love Python"
>>> print(Sting)
I love Python
>>> Sting="""I love Python"""
>>> print(Sting)
I love Python
>>> Sting='''I love Python'''
>>> print(Sting)
I love Python

It may be observed that we have created a string in four different ways each time assigned to
a variable with the name String and got it printed. Each time we obtained same output. So,
this is how a variable of String type can be created through mere assignment. Another way to
create a variable of type string is just by accepting input from the terminal by using the input
statement as illustrated below:
>>> name=input("What is your name?")
What is your name?My name is Ramratan Datta
>>> print(name)
My name is Ramratan Datta

It may be noted that a string is used to generate a prompt for the user to enter inputs also as
as we have used in the input() statement. It may also be printed directly as shown below:

>>> print("What a marvelous piece of work this is!")


What a marvelous piece of work this is!

5.2.1 Empty string.


A pair of quotation marks without anything inside is called an empty string. This is
sometimes required to initialize a variable of type string. So, it is equivalent to 0 used to
initialize a numeric variable. The following figure illustrates its use:

>>> s=''
>>> print(s)

>>> print(s)
a
>>> a=""
>>> c=""""""
>>> print(a)

>>> print(c)

1.2.2 Length of a string


The length of a string means the number of characters included within the quotes or
the number of characters that makes the text including the spaces, if any. The len()
method gives this length instantly as illustrated in the following figure:
>> a=""
> >>> len(a)
0
>>> s="I like Python"
>>> len(s)
13
>>> n='Avagadro'
>>> len(n)
8

1.2.3 Concatenation and repetition


The term concatenation implies string addition i.e. putting strings side by side. Python
supports concatenation with the + operator. In addition, 1 + 1 gives 2; whereas, in
concatenation ‘1’ + ‘1’ generates ‘11’. Different outputs with addition and concatenation
generated by the Python shell are shown in the figure below:
>>> 1+1
2
>>> '1'+'1'
'11'
>>> 'Ram'+'ayan'
'Ramayan'
>>> Ram+ayan
Traceback (most recent call last):
File "<pyshell#31>", line 1, in <module>
Ram+ayan
NameError: name 'Ram' is not defined

The word repetition means recursive duplication of something. In Python, repetition of a


string can be done by using the * operator followed by a number before a string. This is
illustrated below:

>>> st='Ram'
>>> st*3
'RamRamRam'
>>> 'Ram Ram'*5
'Ram RamRam RamRam RamRam RamRam Ram'
>>> 'Ram Ram '*5
'Ram Ram Ram Ram Ram Ram Ram Ram Ram Ram '
1.2.4 The in membership operator
The in membership operator is used to search for the first occurrence of any substring
within a string. The following figure illustrates its use.
>>> st='abcabc'
>>> if 'abc' in st:
print('abc')
abc
>>> s='aaaaaaa'
>>> if 'a' in s:
print('a is in the string')
>>> if 'aa' in s:
print('aa is there in the string')

aa is there in the string

The in operator can also be used with ‘not’ . For example, if ‘I’ not in st …….
1.2.5 Indexing and Slicing
a is in the string
The term ‘index’ is used to point out the offset value of an element in a collection of
elements like
>>> if 'aa' in s: that in a string where each element is a character. The meaning of the
word ‘offset’ is how far away it is situated from the beginning of the collection. As the
print(aaisis situated
first character there in the string')
0 characters away from the beginning of a string, its offset
value is 0; hence its index is also zero. Thus, different characters in a string can be
accessed by using the name of the string immediately followed by its index within
square brackets. This process of referencing different characters in a string is called
indexing. In Python both positive and negative integers can be used as index. Negative
index means from the end position; the last position index being -1.The following
figure shows the indexing process:
>>> st='footbal'
>>> st[0]
'f'
>>> st[1]
'o'
>>> st[6]
'l'
>>> str[-1] # This indicates the last character
'r'
>>> str[-2] # This points out the second to the last character
'e'
>>> str[-34] # As indexing with negative values starts from -1, -34 will mean the second
character.
''
>>> str[-35]
'A'
#indexing.py
str="A thing of beauty is a joy for ever"

for i in range(len(str)):

print(str[i],end=' ')

Output: A t h i n g o f b e a u t y i s a j o y f o r e v e r

The term ‘slice’ means ‘portion’. So, slicing of a string refers to the task of taking a portion or
part from it. The slicing operator is a combination of index and range operator(:) as
illustrated below:
>>> str
'A thing of beauty is a joy for ever' # The stored string is displayed
>>> str[3:17] # This is to show characters consecutively from index position 3 to the index
position 17
'hing of beauty'
>>> str[2:17]
'thing of beauty'
>>> str[:17] # This implies: from the beginning index position{When it is not mentioned) to the
position 17.
'A thing of beauty'
>>> str[19:] # This implies from the index position 19 to the end(when the end index is not
mentioned)
's a joy for ever'
>>> str[18:]
'is a joy for ever'

# We can leave either the starting or ending locations blank. If we leave the starting location
blank, it defaults to the starting location of the string. If we leave the ending location blank, it
defaults to the end of the string.

>>> str[:] # This implies: for all index positions


'A thing of beauty is a joy for ever'
>>> str[5:20:2] # This means that the starting index will be 5 followed by step 2 jumping until 20
'n fbat s' # This will be the output. The third argument is optional as in the range function. It
implies the step value by which the index value is to be incremented.
Example with another string.
>>> stg='abcdefghijklmnopqrstuvwxyz'
>>> stg[0:25:2]
'acegikmoqsuwy'
>>> stg[2:26:3]
'cfilorux'
>>> stg[: :-1]
'zyxwvutsrqponmlkjihgfedcba' # It may be noted that a negative step reverses the string.
1.2.6 Changing individual characters of a string
Strings in Python are immutable. This means that once a string is defined, we cannot
change any part of by assigning a new value to an indicated location. If we try to do
that, the system will throw error messages as shown in the figure below. However, it
can be done by following a trick as generalized below:
String_variable[: index of the location-the –value-of- which-is –required-to-
be-changed] + ‘character to be assigned’+string_variable[index of the next location: ]
This is also illustrated in the figure below:

>>> str='abcde'
>>> str[3]='x'
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
str[3]='x'
TypeError: 'str' object does not support item assignment
>>> str[:3]+'x'+str[4:]
'abcxe'

So, it is seen that deletion or modification of individual characters is not allowed normally in
Python. Nevertheless, we can delete a whole string by using the keyword del if the string is
not required any longer. For instance,

>>> strn
['Alas!', 'I', 'am', 'undone.']
>>> del strn
>>> strn
Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
strn
NameError: name 'strn' is not defined

1.2.7 String Methods


A string method is a built-in function that returns information that returns
information according to its purpose. In Python, there are multitudes of built-in
functions available in Python. We mention here the important ones in the figure
below:

Method Functionality

lower() Returns the string with each of the characters in lowercase form. For
instance, >>> strn='ABCD'
>>> strn.lower()
'abcd'
upper() Returns the string with each of the characters in uppercase form.
replace(x,y) Returns the string with each of the occurrences of x with y. For instance,
>>> stn.replace('e','f') # This is to replace every occurrence of ‘e’ with ‘f’;
we we get, 'affbbcbf'. As another example.
>>> strn.replace('Teacher','Mentor')
'He is our Mentor'

NOTE: All the above functions do not change the original string unless the
changed
Value is reassigned to the string variable.
count(x) It is to count the number of occurrences of ‘x’ in a given string. For
instance, >>> stn='aeebbcbe' >>>x='f' >>> stn.count(x) returns 0; but
>>> x='e'
>>> stn.count(x) returns 3
index(x) Returns the index of the first occurrence of the character in the string. For
instance, stn='aeebbcbe' >>> x='e' >>> stn.index(x) returns 1.
isalpha() Returns True if every character in the string is a letter of the English alphabet.
isdigit(), isnumeric(),isupper(),islower(),isdecimal()
are similar functions.
capitalize() It is to convert the first letter of a string to its uppercase form. For instance,
>>> nam='ramesh' >>> nam.capitalize() returns 'Ramesh'
find(str, Determines if str occurs in string or in a substring of string if starting index
beg = 0 end ‘beg’ and ending index ‘end’ are given and returns index if found and -1
= otherwise.
len(string))

index(str, It is same as find(), but raises an exception if str is not found.


beg = 0, end
=
len(string))

title() It returns "titlecased" version of string, that is, all words begin with
uppercase and the rest in lowercase. For example, >>> book_title='the art
of programming through python'
>>> book_title.title()
'The Art Of Programming Through Python'
zfill (width) It returns the original string leftpadded with zeros to a total of width
characters; it is intended for numbers, it retains any sign given (less one
zero).
swapcase() This function is used to change the existing case of each of the characters in
In a string. For instance,
>>> str='abc sIR IS OUR PYTHON TEACHER'
>>> str.swapcase()
'ABC Sir is our python teacher'
Split() This method breaks a string into list of substrings separated by white
spaces. The white spaces include spaces, tabs or newline characters. If the
substrings consist of punctuation marks, the substrings will accompany
them also. For instance,
>>> strng='Alas! I am undone.'
>>> strng.split()
['Alas!', 'I', 'am', 'undone.']
Join() The join() method joins the substrings in a string with a specified character
in between. Its syntax is: character to be placed in between
substrings.join(string). For example,
>>> strn
['Alas!', 'I', 'am', 'undone.']
>>> ' '.join(strn)
'Alas! I am undone.'
>>> ''.join(strn)
'Alas!Iamundone.'
>>> '*'.join(strn)
'Alas!*I*am*undone.'
strip() This method removes all the leading and trailing spaces existing in a string.

rstrip() This method removes trailing spaces in a string.


>>> s=' Hello Python '
>>> s.rstrip()
' Hello Python'
lstrip() This method removes leading spaces in a string. For instance,
>>> s.lstrip()
'Hello Python '

maketrans() It is used to create a one -to –one translation table for a specified string.
For example,
table=strn.maketrans("aeiou", "AEIOU")
Here, the translation table is for the string strn.
1.2.8 String formatting in Python
Sometimes, we come across strings which cannot be written normally as a string using
single or double quotes. For instance, we consider such a string that goes as the
following one:
He said to me, “What’s going on here?”
If we write: s='He said to me,"What's going on here?"' , the Python shell will respond:
SyntaxError: invalid syntax
Again, if we write: s="He said to me,"What's going on here?"" , the same error
message will be generated. Now, there is still an alternative, let us try with the
following:
s='''He said to me,"What's going on here?"'''
This is accepted. So, enclosing the string within triple quotes solves the problem.
There is another way out in which we use escape characters either for the single
quotes or for the double quotes. When the single quotes are escaped, the string can
be enclosed within single quotes and when the double quotes are escaped, the string
can then be escaped within double quotes as shown below:

s='He said to me,"What\'s going on here?"'

s="He said to me,\"What's going on here?\""


Here the symbol’\’ acts as escape character to imply that the character before which it
is placed must not be interpreted as a normal quotation sign. An escape sequence
always starts with a backslash and it is interpreted in a different way. If we use single
quote to represent a string, all the single quotes inside the string must be escaped.
Similar is the case with double quotes.

A list of all the escape sequences supported by Python have been listed below.

Escape Sequence Functionality

Ignores the backslash and newline. Example with and without


\newline escape sequence:

>>> x='His Mobile number is: 9432487011\n7980468985'


>>> print(x)
His Mobile number is: 9432487011
7980468985
>>> x='His Mobile number is: 9432487011\\n7980468985'
>>> print(x)
His Mobile number is: 9432487011\n7980468985
Prints the backslash. Example:
\\ is Mobile number is: 9432487011\7980468985
>>> x='His Mobile number is: 9432487011\7980468985'
>>> print(x)
His Mobile number is: 9432487011980468985

\’ Single quote. Example shown above.

\’’ Double quote. Example shown above.

\a ASCII Bell

\b ASCII backspace

\f ASCII formfeed

ASCII Linefeed
\n

ASCII Carriage Return


\r

ASCII Horizontal tab


\t

ASCII vertical tab


\v

Character with octal value 000. For example.


\000 >>>
print('\111\040\114\157\166\145\040\120\171\164\150\157\156')
I Love Python
Character with Hexadecimal value HH
\xHH

1.2.8.1 Raw string to ignore escape sequence.


Sometimes, we may like to keep the used escape sequences as they are in the
string. This can be done by declaring the string a raw one. A string is declared as
raw if we put ‘r’ or ‘R’ without the quotes before the string. For example,

>>> print(r" I love my Country.\n My beloved country is India")


I love my Country.\n My beloved country is India # This is a raw string
>>> print(" I love my Country.\n My beloved country is India") # This is the string
with the escape sequence in action. The difference is clearly depicted.
I love my Country.
My beloved country is India

1.2.9 Translating characters in a string

Python supports a translate() method on the string type which allows one to specify the
translation table (used for replacements) as well as any characters which should be deleted in
the process. The format of the method is:
string.translate(table[, deletechars])
Parameter Description table It is a lookup table that defines the mapping from one character
to another. deletechars is a list of characters which are to be removed from the string.

The maketrans method (str.maketrans in Python 3 and string.maketrans in Python 2) allows


us to generate a translation table as illustrated earlier.

>>>strn='This is a Python String'


>>> T=str.maketrans("AEIOU","aeiou")
>>> strn.translate(table)
'ThIs Is A PythOn StrIng' is the output which is a translated copy of the original
string.

1.2.10 The format() Method for Formatting Strings


The format() is a very versatile and strong method for formatting a string in Python.
Here, curly braces {} are used as placeholders or replacement fields which get
replaced with the corresponding strings written within the format method. There are
three ways to format in this method as illustrated below:

1. When we define a string with simple place holders as shown below:


>>> strr='The names of the three students are: {},{},{}'
Now, let us write our print statement as under:
>>> print(strr.format('Rama','Ramesh','Shyama'))
Then the generated output will be names in the nomal order mentioned as shown
below:
The names of the three students are: Rama,Ramesh,Shyama

It means that the strings mentioned within format method will be taken sequentially
to replace the placeholders.
The string with the placeholders can also be written directly in the print() statement as
illustrated below:

>>> print('The names of the students are: {},{} and


{}'.format('Rama','Ramesh','Shyama'))
The output:
The names of the students are: Rama,Ramesh and Shyama

2. When the placeholders contain index value of the strings, 0 for the first one, 1 for
the second one and so on, the strings will be printed accordingly. This is depicted
below:
>>> strr='The names of the three students are: {1},{0},{2}'

>>> print(strr.format('Rama','Ramesh','Shyama'))
OUTPUT: The names of the three students are: Ramesh,Rama,Shyama

3. If we plan to assign keywords to the strings then the keywords are written within
the placeholders and printing of the output occurs accordingly. This is illustrated
below:

>>> trr='The names of the three students are: {i},{j},{k}'


>>> print(trr.format(k='Rama',j='Shyama',i='Ramesh'))
The names of the three students are: Ramesh,Shyama,Rama

We can also use string variables in place of the string literals as illustrated below:

>>> a="Mahesh"
>>> b="Tapesh"
>>> c="Bidesh"
>>> strr='The names of the three students are: {},{},{}'
>>> print(strr.format(a,b,c))

OUTPUT: The names of the three students are: Mahesh,Tapesh,Bidesh


>>> strr='The names of the three students are: {1},{0},{2}'
>>> print(strr.format(a,b,c))
Output: The names of the three students are: Tapesh,Mahesh,Bidesh
>>> strr='The names of the three students are: {i},{j},{k}'
>>> print(trr.format(k=a,j=b,i=c))
Output: The names of the three students are: Bidesh,Tapesh,Mahesh

The general format of a replacement field is shown below:

Replacement_field ::= “{“ [field_name] [“!” conversion] [ “:” format_spec] “}”

field_name ::= arg_name (“.” Attribute_name | “[“ element_index “]”) *

arg_name ::=[identifier|integer]

attribute_name ::= identifier

element_index ::= integer| index_string

index_string ::= <Any source character except “]”> +

conversion ::= “r” |”s”

format_spec ::= [[fill]align][#][0][width][type]

fill ::=<any character>

align=”<”|”>” |”=” |”^”

sign ::= “+”|”-“|” “

width ::= integer

precision ::=integer

type ::=”b”|”c” |”d”| “e”|”E” |”f” |”F”|”g”|”G”|”n”|”o”|”s”|”x”|”X”|”%”

The syntax implies that the replacement_field or the placeholder can optionally contain a
field name that points out the object the value of which is required to be formatted and the
field is substituted with the value in the output. The fieldname can be optionally followed by
a conversion_field, which is to be preceded by a note of exclamation: ‘!’ and a format_spec
preceded by a colon:’:’ . These are the non-default values of the placeholder. The conversion
flag ‘!s’ calls str() and ‘ ! r’ calls repr() where repr() returns a string containing a printable
representation of an object. Let us have some more examples:
Let us use an alignment directive. The format() method is very useful to modify the alignment
of a string. The general structure of a format expression is as shown below:

:[fill_char][alignment _operator][width]

where alignment_operator is one of ‘<’, ‘>’, ‘^’ and ‘=’ and the fill_char is the character
used for padding the value being formatted. If the fill_char is omitted, the remaining
width is filled up with whitespaces.

‘<’ is used for left alignment of the text within the mentioned width having the fill
character on the right to fill up the rest of the width. For example,

>>> '{:*<20}'.format('INTRODUCTION')

'INTRODUCTION********'

‘>’ is used for right alignment of the text within the mentioned width and the fill
character is placed on the left to fill up the rest of the width. For example,

>>> '{:*>12} Note'.format('Important')

'***Important Note'

‘^’ is used for centering the text padded with the given character on both sides to fill up
the width. For example.

>>> '{:*^40}'.format('Welcome to Python')

'***********Welcome to Python************'

‘=’ is used only with numeric types to perform padding with the fill character to fill up the
gaps before the given number for the given width. In case of a signed number, the fill
character comes after the sign to fill up the given width.
>>> '{:*=8}'.format(-5250)
'-***5250'
>>> '{:*=8.2}'.format(+5250.50)
'*5.3e+03'
>>> '{:*=10.2f}'.format(+5250.50)
'***5250.50'
5.2.11 String Formatting Operators
One of the nicest features of Python is the string format operator: %. This operator is
unique to strings in Python and it opens up a new domain of formatting which are akin
to those available in the C programming language with the printf() family of functions.
Let us have a look at the following Python Statemwnt:

print("%s became a legend at the age of %d"%('Maradona',18))


Live Demo
The execution of the above code generates the following output:

Maradona became a legend at the age of 18

The following table shows the symbols that can be used with the % operator.

Format Symbol Converted data type with example

%c, shows Character; e.g. >>> print('The result is %c'%'d')


the ASCII The result is d
equivalent >>> print('The result is %c'%97)
character if The result is a
a number
is used.

%s String via str() before formatting

%i Signed decimal integer; e.g. >>> n=101101


print('The value is:%d'%n)
The value is:101101
But, >>> print('The decimal equivalent value
is:%i'%0b101011) <= The number consisting of 0s and
1s preceded by 0b is treated as a binary number which
is converted to its decimal equivalent before printing.
So, the output will be:
The decimal equivalent value is:43
%d Signed decimal integer. Same example is applicable.

%u Unsigned decimal integer

%o Octal integer; e.g.

>>> print('The number stored is:%o'%10) returns


The number stored is:12<= Octal equivalent of 10.

%x Lowercase hexadecimal symbols

%X Uppercase hexadecimal symbols; e.g.

>>> print('The number stored is:%X'%29)

The output will be uppercase Hexadecimal equivalent


no. as shown below.

The number stored is:1D

%e Numbers in exponential notation with lowercase ‘e’.

%E Numbers in exponential notation with Uppercase ‘E’.

%f or %F Floating point real number up to six decimal places by


default.

%G The shorter form of %f and %E up to five digits after


the decimal point, by default and a maximum of 8
digits; e.g. >>> print('The value is
%G'%5.123456789654321). The printed output will be:
The value is 5.12346
>>> print('The value is %2.10G'%5.123456789654321)
The output:
The value is 5.12345679
%g The shorter form of %f and %e up to five digits after
the decimal point, by default. Example, same as above
ones.

The following table shows other supported flag symbols along with the format symbols in
the preceding table.

Flag Symbol Functionality with examples

* Used to specify the width or precision of a float number as desired; e.g.


>>>x=5.123456789654321
>>> print('The value is %.*f'%(5,x)); Here 5 is the number of digits after the
decimal point. The output will be:
The value is 5.12346
>>> y=3
>>> print('The value is %.*f'%(y,x)); The width can be represented with a
variable also. So the output in this case will be:
The value is 5.123
- This is used for the left justification of numbers printed which are right justified
by default; e.g. >>> print('%5d'%z)
6
>>> print('%-5d'%z)
6
+ Used to display the sign; e.g. >>> p=-5
>>> print('The value is: %+d'%p)
The value is: -5
>>> q=8
>>> print('The value is: %+d'%q)
The value is: +8
<space> A space after the % sign will print a positive number preceded by a space;e.g.
>>> print('The value is:% d'%q)
The value is: 8
>>> print('The value is:% d'%p)
The value is:-5
# Adds the Octal leading zero followed by ‘o’ before printing an octal number.
Similarly, adds the Hexadecimal leading zero followed by ‘x’ or ‘X’ as per the
format specification; e.g.,

>>> print('The value is:%#o'%10)


The value is:0o12
>>> print('The value is:%#X'%29)
The value is:0X1D
0 Pads integers with 0 from the left instead of spaces; e.g.
>>> print('The value is:%05d'%q)
The value is:00008
However, the in case of real numbers, the zero padding is done to the right;
e.g., >>> print('The value is:%05f'%6.789)
The value is:6.789000
>>> print('The value is:%05.8f'%6.789)
The value is:6.78900000
% It is printed when %% is written

(dictionary It is used to print the value corresponding to the key value from a defined
key) Dictionary type data structure(to be covered later).

m.n This is used to mention the width of a field where m implies the minimum total
width and n indicates number of digits after the decimal point(if applicable).
Examples shown above.

1.2.11 Formatting literals with f-string.


Literal format strings have been made available from Python 3.6 upwards. Here the
.format() is applied by prepending the beginning of a string with the letter ‘f’ with all
variable in the current scope. For example,
>>> p=25
>>> f'Price is ${p}'
'Price is $25'
>>> st='Humpty Dumpty'
>>> f'{st} sat on a wall'
'Humpty Dumpty sat on a wall'

Formatting with ‘f’ works well with advanced format string too including dot notation
and alignment operators as illustrated below:
>>> f'{st:*^30s}''sat on a wall'
'********Humpty Dumpty*********sat on a wall'
The dot notation is used to express precision of a float value. It takes the following
format:
f{value:[width].[precision]}
Where,
 value is any expression that evaluates to a number,
 The optional width specifies the total number of character positions used to
display, but if value needs more space than the specified width then the
additional space is used;
 The optional Precision is used to specify the number of character positions
after the decimal point, if not used ,all the available digits will be shown.
These are illustrated below:
>>> f'{v:10.2f}' will return:
' 234.57'
>>> f'{v:10.2}' will return :
' 2.3e+02'
>>> f'{v:.2f}'
'234.57'
>>> f'{v:10}'
' 234.567'

1.3 Illustrative problems with solutions

Problem 5.3.1 Let us a program to count number of vowels in a given string.

Task Analysis:

while(True):
w=input("Enter any string")
v='aeiouAEIOU'
l=len(w)
vc=0
for i in w:
if i in v:
vc+=1
print("The number of vowels in the string is: ",vc)
ch=input("continue? Enter y for yes and n for No=> ")
if ch=='n' or ch.upper()=='N':
break
1.3.2 A program is required to be developed for abbreviating a string as illustrated below:
Damodar Valley Corporation will be abbreviated to DVC.

Task Analysis: The desired abbreviation can be done by concatenating all the first
letters of each of the words in the given string. So, a string variable is first initialized
with the first letter of the given string. Next, we check each of the letters of the string
to ascertain whether it is a space or not. If it is a space, then we concatenate with the
next letter of the string which must then be the first letter of the next word, assuming
that the words are separated by a single space and each word starts in an uppercase
letter. In Python, we can also make use of the title () method to convert the first letter
of each of the words in uppercase.
#Abb.py
while True:
strng=input("Enter any string to abbreviate....Press only Enter for none:=>")
if len(strng)==0:
break
strng=strng.title()
abb=strng[0]
for i in range(len(strng)):
if strng[i]==' ':
abb+=strng[i+1]
print("The abbreviated string is: ",abb)

When the above code is run, the displays will occur:


Enter any string to abbreviate....Press only Enter for none:=> Calcutta Electric Supply
Corporation
The abbreviated string is: CESC
Enter any string to abbreviate....Press only Enter for none:=> Anil Bikash Chowdhury
The abbreviated string is: ABC
Enter any string to abbreviate....Press only Enter for none
Enter any string to abbreviate....Press only Enter for none:=> indian administrative service
The abbreviated string is: IAS
Enter any string to abbreviate....Press only Enter for none:=>

1.3.3 A program is required to be developed for abbreviating a string as illustrated below:


(i) Tapan Kumar Ghosh will become T. K. Ghosh
(ii) Ranit Saha will become R. Saha

Task Analysis:
#Nameabb.py
import string
while True:
strng=input("Enter any Name to abbreviate as desired....Press only Enter for
none:=> ")
if len(strng)==0:
break
strng=strng.title()
cnt=strng.count(' ')
abb=strng[0]+'.'
for i in range(len(strng)):
if strng[i]==' ' and cnt>1:
abb+=strng[i+1]+'.'
cnt-=1
elif strng[i]==' ' and cnt==1:
while(i<len(strng)-1):
abb+=strng[i+1]
i+=1

print("The abbreviated string is: ",abb)

When the above script is run, we get the following displays with the desired
output:
Enter any Name to abbreviate as desired....Press only Enter for none:=> anil
bikash chowdhury
The abbreviated string is: A.B.Chowdhury
Enter any Name to abbreviate as desired....Press only Enter for none:=> tapan
kumar ghosh
The abbreviated string is: T.K.Ghosh
Enter any Name to abbreviate as desired....Press only Enter for none:=> pillu vulu
kanti thake parampil usha
The abbreviated string is: P.V.K.T.P.Usha
Enter any Name to abbreviate as desired....Press only Enter for none:=> ranit
saha
The abbreviated string is: R.Saha
Enter any Name to abbreviate as desired....Press only Enter for none:=>
1.3.4 A program is required to be developed to test whether a given word is a palindrome
or not.

#palin.py
while True:
strng=input("Enter any string to test for palindrome....Press only Enter for none:=> ")
if len(strng)==0:
break
str=''.join(reversed(strng))
if (strng==str):
print("It is a Palindrome")
else:
print("It is not a Palindrome")

Here, reversed(string) will generate a list of characters in reverse order. The join(0 method
has been used to combine all the characters to form a single word. Thus we obtain the
reversed form of the given word. Hence the program generates output as under:

Enter any string to test for palindrome....Press only Enter for none:=> madam
It is a Palindrome
Enter any string to test for palindrome....Press only Enter for none:=> book
It is not a Palindrome
Enter any string to test for palindrome....Press only Enter for none:=> malayalam
It is a Palindrome
Enter any string to test for palindrome....Press only Enter for none:=>

1.3.5 A program is required to be developed for counting the frequency of each of the
characters in a given string.
#freq.py
while True:
strng=input("Enter any string to abbreviate....Press only Enter for none:=> ")
if len(strng)==0:
break
y=''
for i in range(len(strng)):
x=strng[i]
if (x in y):
continue
else:
y+=x
cnt=strng.count(x)
print("Frequency of",x,"in",strng, "is",cnt)

Enter any string to abbreviate....Press only Enter for none:=> aabbabcdaddcbee


Frequency of a in aabbabcdaddcbee is 4
Frequency of b in aabbabcdaddcbee is 4
Frequency of c in aabbabcdaddcbee is 2
Frequency of d in aabbabcdaddcbee is 3
Frequency of e in aabbabcdaddcbee is 2
Enter any string to abbreviate....Press only Enter for none:=>

1.3.6 It is required to develop a program to evaluate a binary string into its equivalent
decimal number.
#bin.py
while True:
strng=input("Enter any binary string to evaluate....Press only Enter for none:=> ")
if len(strng)==0:
break
dn=0
for i in range(len(strng)):
b=int(strng[i])
dn=dn+b*2**i
print("The equivalent binary number is: ",dn)
Enter any binary string to evaluate....Press only Enter for none:=> 101
The equivalent binary number is: 5
Enter any binary string to evaluate....Press only Enter for none:=> 1111
The equivalent binary number is: 15
Enter any binary string to evaluate....Press only Enter for none:=> 101101
The equivalent binary number is: 45
Enter any binary string to evaluate....Press only Enter for none:=>

1.3.7 A simple and very old method of sending secret messages is the substitution cipher. In
the method each letter of the alphabet gets replaced by another letter of the
alphabet, say, every a gets replaced with an m, and every b gets replaced by a y, etc.
Write a program to implement this.

#encrypt.py
alphabet = 'abcdefghijklmnopqrstuvwxyz'
key='myzxacbfgilkpostwjnqrvudeh'
while True:
message=input("Enter any message to encrypt....Press only Enter for none:=> ")
if len(message)==0:
break

message=message.lower()
code=''
for c in message:
if c.isalpha():
code=code+key[alphabet.index(c)]

print("The secret message is: ", code)


Learning Outcome of this chapter: Going through this chapter, It is
expected that the reader will learn the following:

 What are strings


 How strings are manipulated
 How to apply different string methods on a given string
 How to print a formatted form of a string in a variety of ways
 How to solve problems with strings

EXERCISES Five

1. A program is required to be written that prompts the user to enter a string. The program
should then print the following:

(a) The total number of characters in the string

(b) The string repeated 5 times

(c) The first character of the string

(d) The first four characters of the string

(e) The last two characters of the string

(f) The string in the reversed form

(g) The ninth character of the string if the string is long enough and a message otherwise

(h) The string with its first and last characters removed

(i) The string in all the letters in capital form

(j) The string with every ‘i’ replaced with an ‘I’

52 CHAPTER 6. STRINGS

(k) The string with every letter replaced by a space

2. A program is required to be written that prompts the user to enter a string and returns the
number of words in the string.
3. It has been observed that programmers often forget to type the closing parentheses when
formulas are entered. Develop a program that asks the user to enter a formula and prints out
whether the entered formula contains the same number of opening and closing parentheses.

4. Develop a program that asks the user to enter a string and prints out whether the string
contains any vowel or not.

5. Develop a program that asks the user to enter a string to create a new string called new_str
from the given string such that the third character is changed to an asterisk and two signs of
exclamation are attached to the end of the string. Finally, the program prints out the
new_str.

6. Develop a program that prompts the user to enter a string str for its conversion to
lowercase by removing all the periods and commas from it, and shows the resulting string.

7. A program is required to be developed for the following outputs out of a given string:

(i) for counting the number of sentences in the given string and
(ii) for counting the number of lines in the given string.

8. In a certain university named TIU, the email addresses of the students end with
@student.tiu.edu, while the email addresses of the professors end with @prof.tiu.edu. It is
required to develop a program that first asks the user the number of email addresses he/she
will enter, and then it will allow the user enter those addresses. After completion of the
entry, the program is required to print out a message showing the number of entered email
address belonging to each category.

9. Develop a program that prompts the user to input a string, then prints out each letter of
the string tripled in a separate line. For instance, if the input is DAD , the output would be

DDD AAA DDD

10. A program is required to be developed for deciphering a given string of code numbers into
its equivalent alphabetic letters by using the following rules:
(i) A number is to be treated as an ASCII decimal value of a character
(ii) 5 is to be added to the value before converting it into a letter
(iii) If addition of 5 takes the new value to some value that exceeds the
range of letters then 10 is to be subtracted from the sum for
translating it into a letter.
(iv) Spaces in it will remain spaces.
(v) Three digits are to be taken at a time for the translation.
Finally , the translated code is to be shown.
1. Develop a program that prompts the user to enter a word that contains a chosen
letter given as input. If the letter is not contained in the word, then the program is
required to generate a message regarding that; otherwise, it will print the part of the
word up to that given letter in a separate line and the rest in the next line. For
example, if the input word is ‘Coward’ and the given letter is ‘w’, then the output
would look like the following one:

Cow
ard

12. Develop a program that prompts the user to enter a word; it then capitalizes every
alternate letter of that word and shows the resulting word. So if the input word is ‘elephant’,
then the out will be: eLePhAnT.

13. It is required to develop a program that prompts the user to enter two strings of equal
length. The program then checks to see if the strings are really of the same length. If they are
not, the program should then print an appropriate message and exit. If they are of the same
length, the program should then concatenate the strings by taking alternate characters from
the two strings and prints the resulting string. For instance, if the user enters ‘Book’ and ‘Star’
the output should be BSotoakr.

14. Let us have a long string of a few sentences as input in a program with some missing
words represented with hyphens. The program will then asks for a few types of words for
insertion in places of the hyphens. The program then replaces the hyphens with the given
words and prints the reconstructed text. The resulting string may be a funny one.
Nevertheless, we need to develop the code.

For instance, Let the input text be: Tiger is a – animal. It likes to eat -. It lives in -.

Now, the questions may be like the following ones:

Enter an adjective: happy


Enter the name of a food item: noodles
Enter the name of a place: city

Now, we have the following reconstructed string: Tiger is a happy animal. It likes to eat
noodles. It lives in city.

15. Develop a program for the following activities:

(a) Without using the in operator, the program asks the user for a string and a letter and
prints out whether or not the letter appears in the string.
(b) Without using the count method, the program asks the user for a string and a letter and
counts how many times the letter occurs in the string.

(c) Without using the index method, the program that asks the user for a string and a letter
and prints out the index of the first occurrence of the letter in the string. If the letter is not in
the string, the program should say so.

16. Write a program that asks the user for a large integer and inserts commas into it
according to the standard convention for commas in large numbers. For instance, if the user
enters 12345678, the output should be 12,345,678.

17. A program is required to be developed for generating all possible permutations of words
with all the letters in the word. For example, if the given word is ‘bit’, the different possible
words will be: bit, tib, tbi, bti, tib, ibt.

18.. One simple way of encrypting a message is by rearranging its characters. One way to
rearrange the characters is to pick out the characters at odd indices, put them first in the
encrypted string, and follow them by the characters at the even positions. For instance, the
message ‘Save our Soul’ would be encrypted as: Sv u oliaeorSu

(a) Develop a program that prompts the user for a string and uses this method to encrypt the
string to show the encrypted message.

(b) Develop a program to decrypt a string that was encrypted with this method.

19. A more general version of the above technique is the rail fence cipher, where instead of
breaking things into evens and odds, they are broken up by threes, fours or something larger.

(a) Develop a program the prompts the user for a string and uses the rail fence cipher in the
threes case to encrypt the string.

(b) Write a decryption program for the threes case.

(c) Write a program that asks the user for a string, and an integer determining whether to
break things up by threes, fours, or whatever. Encrypt the string using the rail-fence cipher.

(d) Write a decryption program for the general case.

20. In calculus, the derivative of x5 is 5x4. The derivative of x3 is 3x2. This pattern continues.
Develop a program that prompts the user for input like x^3 or x^25 and shows the derivative.

21. In algebraic expressions, the symbol for multiplication is often omitted, as in 5x+7y
or5(x+3). Computers cannot operate on those expressions. It is required to develop a
program that prompts the user for an algebraic expression and then inserts the
multiplication symbols where appropriate.

You might also like