Chapter 8: Working with Strings & Standard Functions

Example 8.1, Page number: 236

In [23]:
#Display string without considering NULL character

import sys

#Variable Initialization
name1 = 'SANJAY'
#There is no null termination character in python

#Result
sys.stdout.write("Name1 = %s"%(name1))
Name1 = SANJAY

Example 8.2, Page number: 236

In [21]:
#Display successive strings

import sys

#Variable Initialization
name1 = 'SANJAY'
name2 = 'SANJAY'
#There is no null termination character in python


#Result
sys.stdout.write("Name1 = %s"%name1)
sys.stdout.write("\nName2 = %s"%(name2))
Name1 = SANJAY
Name2 = SANJAY

Example 8.3, Page number: 237

In [24]:
#Print "WELCOME" by using different formats of initialization 

import sys

#Variable Initialization
#in python, string initialization can be done using single quotes and double quotes
arr1 = 'WELCOME'
arr2 = "WELCOME"
arr3 = 'WELCOME'

#Result
sys.stdout.write("\nArray1 = %s"%(arr1))
sys.stdout.write("\nArray2 = %s"%(arr2))
sys.stdout.write("\nArray3 = %s"%(arr3))
Array1 = WELCOME
Array2 = WELCOME
Array3 = WELCOME

Example 8.4, Page number: 238

In [25]:
#Display the string 'PRABHAKAR' using various format specifications

import sys

#Variable Initialization
text = "PRABHAKAR"

#Result
sys.stdout.write("%s\n"%(text))
sys.stdout.write("%.5s\n"%(text))
sys.stdout.write("%.8s\n"%(text))
sys.stdout.write("%.15s\n"%(text))
sys.stdout.write("%-10.4s\n"%(text))
sys.stdout.write("%11s\n"%(text))
PRABHAKAR
PRABH
PRABHAKA
PRABHAKAR
PRAB      
  PRABHAKAR

Example 8.5, Page number: 239

In [27]:
#Print the elements of the character array using while loop.

import sys

#Variable Initialization
text = "HAVE A NICE DAY"
i = 0

#Result
#There is no null character for strings in python

while i < 15:
    sys.stdout.write("%c"%(text[i]))
    i += 1
HAVE A NICE DAY

Example 8.6, Page number: 239

In [28]:
#Print the elements of the character array.

import sys

#Variable Initialization
text = "HAVE A NICE DAY"
i = 0

#Result
#There is no null character for strings in python

while i < 15:
    sys.stdout.write("%c"%(text[i]))
    i += 1
HAVE A NICE DAY

Example 8.7, Page number: 241

In [1]:
#Count the number of characters in a given string

import sys

#Variable Initialization
text = raw_input("Type Text Below")

#Calculation
len1 = len(text)    #since len in a built in function in python, len1 is used

#Result
sys.stdout.write("Length of String = %d"%(len1))
Type Text BelowHello
Length of String = 5

Example 8.8, Page number: 241

In [2]:
#Determine the length of the string
#and find its equivalent ASCII codes.

import sys


#Variable Initialization
name = raw_input("Enter your name : ")
l = len(name)

#Result
sys.stdout.write("Your Name is %s & "%(name))
sys.stdout.write("it contains %d characters"%(l))
sys.stdout.write("\n\nName & it's Ascii Equivalent.\n")
sys.stdout.write("=====================================\n")

for i in range(0,l):
    sys.stdout.write("\n%c\t\t%d"%(name[i],ord(name[i])))   #ord() function is used to get the ASCII value of a character
Enter your name : SACHIN
Your Name is SACHIN & it contains 6 characters

Name & it's Ascii Equivalent.
=====================================

S		83
A		65
C		67
H		72
I		73
N		78

Example 8.9, Page number: 242

In [3]:
#Remove the occurrences of 'The' word from entered text

import sys

#Variable Initialization
j = 0
line = raw_input("Enter Text Below.")
l = len(line)
line2 = ['0' for i in range(0,80)]
i = 0

#Calculation
while i < l:
    if (i >= l-4 or l ==3) and (line[l-4] == ' ' and line[l-3] == 't' and line[l-2] == 'h' and line[l-1] == 'e'):
        continue
    if line[i] == 't' and line[i+1] == 'h' and line[i+2] == 'e' and line[i+3] == ' ':
        i += 3
        continue
    else:
        line2[j] = line[i]
        j += 1
    i += 1
        
#Result
sys.stdout.write("\nText With 'The' -: %s"%(line))
sys.stdout.write("\nText Without 'The' -: ")
for l in range(0,j):
    sys.stdout.write("%c"%(line2[l]))
        
Enter Text Below.Printf write data to the screen.

Text With 'The' -: Printf write data to the screen.
Text Without 'The' -: Printf write data to  screen.

Example 8.10, Page number: 243

In [4]:
#Delete all the occurrences of vowels in a given text.

import sys

#Variable Initialization
j = 0
line = raw_input("Enter Text Below.")

#Calculation
for i in range(0,len(line)):
    if line[i] == 'a' or line[i] == 'e' or line[i] == 'i' or line[i] == 'o' or line[i] == 'u':
        continue
    else:
        line2[j] = line[i]
        j += 1
      
#Result
sys.stdout.write("Text With Vowels -:  %s"%(line))
sys.stdout.write("\nText Without Vowels -:  ")
for l in range(0,j):                                  #There is no null terminating character in python, so we have to specify length
    sys.stdout.write("%c"%(line2[l])) 
        
Enter Text Below.Have a nice day.
Text With Vowels -:  Have a nice day.
Text Without Vowels -:  Hv  nc dy.

Example 8.11, Page number: 244

In [5]:
#Find the length of characteres in a given string including and excluding spaces.

import sys

#Variable Initialization
i = 0
len1 = 0       #Since len is a built in function in python, len1 is used
ex = 0

text = raw_input("Enter Text Here : ")

#Calculation
while i != len(text)-1:           #There is no null terminating character in python.
    if text[i] == ' ':
        ex += 1
    else:
        len1 += 1
    i += 1
    
#Result
sys.stdout.write("\nLengh of String Including Spaces : %d"%(len1+ex))
sys.stdout.write("\nLengh of String Excluding Spaces : %d"%(len1))
Enter Text Here : Time is Money.

Lengh of String Including Spaces : 13
Lengh of String Excluding Spaces : 11

Example 8.12, Page number: 245

In [6]:
#Display the length of entered string and display it as per output shown.

import sys

#Variable Initialization
string = raw_input("Enter a String")
ln = len(string)

#Result
sys.stdout.write("\nLength of Given String : %d"%(ln))
sys.stdout.write("\nSequence of Characters Displayed on Screen")
sys.stdout.write("\n======== == ========== ========= == ======")
sys.stdout.write("\n\n")

for c in range(0,ln-2+1):
    d = c + 1
    sys.stdout.write("\t%.*s\n"%(d,string))

for c in range(ln,0-1,-1):
    d = c + 1
    sys.stdout.write("\t%.*s\n"%(d,string))
Enter a StringHAPPY

Length of Given String : 5
Sequence of Characters Displayed on Screen
======== == ========== ========= == ======

	H
	HA
	HAP
	HAPP
	HAPPY
	HAPPY
	HAPP
	HAP
	HA
	H

Example 8.13, Page number: 247

In [7]:
#Copy contents of one string to another string by using strcpy()

import sys

#Variable Initialization
ori = raw_input("Enter Your Name : ")

#Process
dup = ori                  #In python, string values can be simply copied using assignment operator

#Result
sys.stdout.write("Original String : %s"%(ori))
sys.stdout.write("\nDuplicate String : %s"%(dup))
Enter Your Name : SACHIN
Original String : SACHIN
Duplicate String : SACHIN

Example 8.14, Page number: 247

In [8]:
#Copy contents of one string to another, without strcpy() function.

import sys

#Variable Initialization
ori = raw_input("Enter Your Name : ")

#Calculation
dup = ori                  #In python, string values can be simply copied using assignment operator
    
#Result
sys.stdout.write("Original String : %s"%(ori))
sys.stdout.write("\nDuplicate String : %s"%(dup))
Enter Your Name : SACHIN
Original String : SACHIN
Duplicate String : SACHIN

Example 8.15, Page number: 248

In [10]:
#Copy source string to destination string upto a specified length.

import sys

#Variable Initialization
str1 = raw_input("Enter Source String : ")
str2 = raw_input("Enter Destination String : ")
n = int(raw_input("Enter Number of Characters to Replace in Destination String :"))

#Calculation
str2 = str1[:n] + str2[n:]         #Since python strings are not mutable, first and second array elements to be added to make a new one
    
sys.stdout.write("Source String -: %s"%(str1))
sys.stdout.write("\nDestination String -: %s"%(str2))
Enter Source String : wonderful
Enter Destination String : beautiful
Enter Number of Characters to Replace in Destination String :6
Source String -: wonderful
Destination String -: wonderful

Example 8.16, Page number: 249

In [11]:
#Compare the two string using stricmp() function. 

import sys

#Variable Initialization
sr = raw_input("Enter String(1) :")
tar = raw_input("Enter String(2) :")

diff = (sr == tar)           #in python, relational operators can be used directly

if diff == 0:
    sys.stdout.write("The Two Strings are Identical.")
else:
    sys.stdout.write("The Tow Strings are Different")
Enter String(1) :HELLO
Enter String(2) :hello
The Two Strings are Identical.

Example 8.17, Page number: 250

In [13]:
#Perform following.

#  1.  Display the question "What is the Unit of Traffic?"
#  2.  Accept the Answer.
#  3.  If the answer is wrong (other than Earlang) display "Try again!" & continues to answer.
#  4.  Otherwise, if it is correct "Earlang" display the message "Answer is correct".
#  5.  If the user gives correct anser in first two attempts the program will terminate.
#  6.  If the user fails to provide correct answer in three attempts the program itself gives the answer.

import sys

#Calculation & Result
for i in range(0,3):
    ans = raw_input("What is the Unit of Traffic ?")
    
    if ans == "Earlang":
        sys.stdout.write("\nAnswer is Correct.")
    else:
        if i < 3:
            sys.stdout.write("\nTry Again !\n")
            
if i == 3:
    sys.stdout.write("\nUnit of Traffic is Earlang.")
What is the Unit of Traffic ?Earlan

Try Again !
What is the Unit of Traffic ?Earlam

Try Again !
What is the Unit of Traffic ?Earlang

Answer is Correct.

Example 8.18, Page number: 252

In [14]:
#Compare two strings upto specified length.

import sys

#Variable Initialization
sr = raw_input("Enter String(1):")
tar = raw_input("Enter String(2):")
n = int(raw_input("Enter Lenght upto which comparison is to be made"))

#Calculation & Result
diff = (sr == tar[:n])

if diff == 0:
    sys.stdout.write("The Two Strings are Identical upto %d characters."%(n))
else:
    sys.stdout.write("The Two Strings are Different")
    
Enter String(1):HELLO
Enter String(2):HE MAN
Enter Lenght upto which comparison is to be made2
The Two Strings are Identical upto 2 characters.

Example 8.19, Page number: 253

In [15]:
#Compare two strings and display the position in which it is different.

import sys

#Variable Initialization
diff = 0
sr = raw_input("Enter String(1) :")
tar = raw_input("Enter String(2) :")

#Checking
for i in range(0,len(sr)):
    if sr[i] != tar[i]:
        sys.stdout.write("%c  %c\n"%(sr[i],tar[i]))
        diff += 1
        
#Result
if len(sr) == len(tar) and diff == 0:
    sys.stdout.write("\nThe Two Strings are Identical")
else:
    sys.stdout.write("\nThe Two Strings are Different at %d places."%(diff))
Enter String(1) :BEST LUCK
Enter String(2) :GOOD LUCK
B  G
E  O
S  O
T  D

The Two Strings are Different at 4 places.

Example 8.20, Page number: 254

In [16]:
#Convert upper case string to lower case using strlwr().

import sys

#Variable Initialization
upper = raw_input("Enter a string in Upper case :")

#Result
sys.stdout.write("After strlwr() : %s"%(upper.lower()))
Enter a string in Upper case :ABCDEFG
After strlwr() : abcdefg

Example 8.21, Page number: 254

In [17]:
#Convert Lower case string to upper case using strupr()

import sys

#Variable Initialization
upper = raw_input("Enter a string in Lower Case :")

#Result
sys.stdout.write("After strupr() : %s"%(upper.upper()))
Enter a string in Lower Case :abcdefg
After strupr() : ABCDEFG

Example 8.22, Page number: 255

In [18]:
#Display the duplicate string using strdup() function

import sys

#Variable Initialization
text1 = raw_input("Enter Text : ")

#Result
text2 = text1              #in python, a string can be duplicated by just using the assignment operator

sys.stdout.write("Original String = %s\nDuplicate String = %s"%(text1,text2))
Enter Text : Today is a Good Day.
Original String = Today is a Good Day.
Duplicate String = Today is a Good Day.

Example 8.23, Page number: 256

In [19]:
#Find first occurrence of a given character in a given string. 

import sys

#Variable Initialization
string = raw_input("Enter Text Below :")
ch = raw_input("Character to find :")

#Result
chp = string.count(ch)
if chp:
    sys.stdout.write("Character %s found in string"%(ch))
else:
    sys.stdout.write("Character %s not found in string"%(ch))
Enter Text Below :Hello Begineers.
Character to find :r
Character r found in string

Example 8.24, Page number: 257

In [20]:
#Find first occurrence of a given character in a given string and display the memory location. 

import sys

#Variable Initialization
line1 = raw_input("Enter Text :")
line2 = raw_input("Enter Character to find from the text : ")

for i in range(0,len(line1)):
    sys.stdout.write("%c  %d\n"%(line1[i],id(line1[i])))

chp = line1.count(line2)
if chp:
    sys.stdout.write("\nAddress of first %s returned by strchr() is %d"%(line2,id(line1[chp])))
else:
    sys.stdout.write("'%s' String is not present in Given String "%(line2))
Enter Text :HELLO
Enter Character to find from the text : L
H  20382328
E  20384080
L  19678272
L  19678272
O  20198416

Address of first L returned by strchr() is 19678272

Example 8.25, Page number: 258

In [21]:
#Find the occurrence of second string in the first string.

import sys

#Variable Initialization
line1 = raw_input("Enter Line1 :")
line2 = raw_input("Enter Line2 :")

#Calculation & Result
chp = line1.count(line2)

if chp:
    sys.stdout.write("'%s' String is present in Given String."%(line2))
else:
    sys.stdout.write("'%s' String is not present in Given String."%(line2))
Enter Line1 :INDIA IS MY COUNTRY.
Enter Line2 :INDIA
'INDIA' String is present in Given String.

Example 8.26, Page number: 259

In [22]:
#Append second string at the end of first string using strcat() function

import sys

#Variable Initialization
text1 = raw_input("Enter Text1 :")
text2 = raw_input("Enter Text2 :")

#Calculation and Result
text1 = text1 + " " + text2        #in python, '+' operator can also be used for string concatenation

sys.stdout.write("%s"%(text1))
Enter Text1 :I Am
Enter Text2 :an Indian
I Am an Indian

Example 8.27, Page number: 259

In [23]:
#Concatenate two strings without use of standard functions.

import sys

#Variable Initialization
fname = raw_input("First Name :")
sname = raw_input("Second Name :")
lname = raw_input("Last Name :")

#Calculation
name = fname + " " + sname + " " + lname

#Result
sys.stdout.write("\nComplete Name After Concatenation.\n")
sys.stdout.write("%s"%(name))
First Name :MOHAN
Second Name :KARAMCHAND
Last Name :GANDHI

Complete Name After Concatenation.
MOHAN KARAMCHAND GANDHI

Example 8.28, Page number: 261

In [24]:
#Append second string with specified (n) number of characters at the end of first string.

import sys

#Variable Initialization
text1 = raw_input("Enter Text1 :")
text2 = raw_input("Enter Text2 :")
n = int(raw_input("Enter Number of Characters to Add :"))

#Calculation & Result
text1 = text1 + " " + text2[:n]

sys.stdout.write("%s\n"%(text1))
Enter Text1 :MAY I
Enter Text2 :COME IN ?
Enter Number of Characters to Add :4
MAY I COME

Example 8.29, Page number: 261

In [25]:
#Reverse of the given string.

import sys

#Variable Initialization
text = raw_input("Enter String")

#Result
sys.stdout.write("Reverse String\n")
text = text[::-1]
#This is extended slice syntax. It works by doing [begin:end:step] 
#by leaving begin and end off and specifying a step of -1, it reverses a string.

sys.stdout.write("%s"%(text))
Enter StringABCDEFGHI
Reverse String
IHGFEDCBA

Example 8.30, Page number: 262

In [26]:
#Reverse of the given string.

import sys

#Variable Initialization
text = raw_input("Enter String")
i = 0

#Result
while i < len(text):
    sys.stdout.write("\n%c is stored at location %d"%(text[i],id(text[i])))
    i += 1
    
sys.stdout.write("\nReverse String :- ")
text = text[::-1]
#This is extended slice syntax. It works by doing [begin:end:step] 
#by leaving begin and end off and specifying a step of -1, it reverses a string.

sys.stdout.write("%s"%(text))

i = 0
while i < len(text):
    sys.stdout.write("\n%c is stored at location %d"%(text[i],id(text[i])))
    i += 1

#Memory address differs in different systems
Enter StringABC

A is stored at location 20383432
B is stored at location 20198992
C is stored at location 20199040
Reverse String :- CBA
C is stored at location 20199040
B is stored at location 20198992
A is stored at location 20383432

Example 8.31, Page number: 263

In [27]:
#Replace (set) given string with given symbol. 

import sys

#Variable Initialization
string = raw_input("Enter String :")
symbol = raw_input("Enter Symbol for Replacement : ")

#Result
sys.stdout.write("Before strset(): %s\n"%(string))
string = symbol*len(string)

sys.stdout.write("After strset() : %s"%(string))
Enter String :LEARN C
Enter Symbol for Replacement : Y
Before strset(): LEARN C
After strset() : YYYYYYY

Example 8.32, Page number: 264

In [28]:
#Replace (set) given string with given symbol for given number of arguments.

import sys

#Variable Initialization
string = raw_input("Enter String :")
symbol = raw_input("Enter Symbol for Replacement : ")
n = int(raw_input("How many String Character to be replaced."))

#Result
sys.stdout.write("Before strset() : %s\n"%(string))

string = symbol * n + string[n:]
sys.stdout.write("After strset() : %s\n"%(string))
Enter String :ABCDEFGHIJ
Enter Symbol for Replacement : +
How many String Character to be replaced.4
Before strset() : ABCDEFGHIJ
After strset() : ++++EFGHIJ

Example 8.33, Page number: 265

In [29]:
#Display the position from which the two strings are different.

import sys

#Variable Initialization
stra = raw_input("First String : ")
strb = raw_input("Second String : ")

#There is no built in function for python to check upto which position the strings are equal.
for length in range(min(len(stra), len(strb))):
        if stra[length] != strb[length]:
            break

sys.stdout.write("After %d Characters there is no match."%(length))
First String : GOOD MORNING
Second String : GOOD BYE
After 5 Characters there is no match.

Example 8.34, Page number: 266

In [30]:
#Print given string from first occurrence of given character.

import sys

#Variable Initialization
text1 = raw_input("Enter String : ")
text2 = raw_input("Enter Character :")

for length in range(0,len(text1)):
        if text1[length] == text2[0]:
            break
            
sys.stdout.write("String from given Character : %s"%(text1[length:]))
Enter String : INDIA IS GREAT
Enter Character :G
String from given Character : GREAT

Example 8.35, Page number: 266

In [32]:
#Count a character that appears in a given text

import sys

#Variable Initialization
i = 0
count = 0
text = raw_input("Type Text Below.")
find = raw_input("Type a character to count : ")

#Calculation
while i < len(text):             #There is no null terminating character for python string
    if text[i] == find:
        count += 1
    i += 1
    
#Result
sys.stdout.write("\nCharacter (%s) found in Given String = %d Times."%(find,count))
Type Text Below.Programming
Type a character to count : m

Character (m) found in Given String = 2 Times.

Example 8.36, Page number: 267

In [33]:
#Count the character 'm' in a given string.

import sys

#Variable Initialization
count = 0
text = raw_input("")  #it is easy to get string at once in python

#Result
sys.stdout.write("%s"%(text))

for i in range(0,len(text)):
    if text[i] == '\n':
        break
    else:
        if text[i] == 'm':
            count += 1
            
sys.stdout.write("\n\nCharacter 'm' Found in Text = %d times."%(count))
Programming is a skill.
Programming is a skill.

Character 'm' Found in Text = 2 times.

Example 8.37, Page number: 268

In [46]:
#Count the characters 'm', 'r', and 'o' that appears in a string without using any functions

import sys

#Variable Initialization
text = "Programming is good habit"
m = 0
o = 0
r = 0

#Calculation
for i in range(0,len(text)):
    if text[i] == 'm':
        m += 1
    if text[i] == 'r':
        r += 1
    if text[i] == 'o':
        o += 1

#Result
sys.stdout.write("\nCharacter 'm' Found in Text = %d times.\n"%(m))
sys.stdout.write("\nCharacter 'r' Found in Text = %d times.\n"%(r))
sys.stdout.write("\nCharacter 'o' Found in Text = %d times."%(o))
Character 'm' Found in Text = 2 times.

Character 'r' Found in Text = 2 times.

Character 'o' Found in Text = 3 times.

Example 8.38, Page number: 269

In [34]:
#Copy contents of one string to another string

import sys

#Variable Initialization
ori = raw_input("Enter Your Name :")

#Copying
#Since strings in python are immutable, individual character assignment is not possible.
#but assignment operator simply copies the entire string to another

dup = ori

#Result
sys.stdout.write("Original String : %s"%(ori))
sys.stdout.write("\nDuplicate String : %s"%(dup))
Enter Your Name :SACHIN
Original String : SACHIN
Duplicate String : SACHIN

Example 8.39, Page number: 270

In [35]:
#Palindrome or not.

import sys

#Variable Initialization
i = 0
str1 = raw_input("Enter the word : ")   #Since str is a keyword in python, str1 is used
j = len(str1)-1

#Calculation
while i < j:
    if str1[i] == str1[j]:
        test = 1
    else:
        test = 0
        break
    i += 1
    j -= 1
    
#Result
if test == 1:
    sys.stdout.write("Word is palindrome.")
else:
    sys.stdout.write("\nWord is not Palindrome.")
Enter the word : ABBA
Word is palindrome.

Example 8.40, Page number: 271

In [53]:
#Compare the string using strcmp() function and display their ASCII difference.

import sys

#Variable Initialization
a1 = "NAGPUR"
a2 = "NAGPUR"
a3 = "PANDHARPUR"
a4 = "KOLHAPUR"
a5 = "AURANGABAD"
a6 = "HYDERABAD"

#Calculation
#There is no built in function which returns the ascii value differece of two strings
#ord function gives the ascii value of a character
c1 = ord(a1[0]) - ord(a2[0])
c2 = ord(a3[0]) - ord(a4[0])
c3 = ord(a5[0]) - ord(a6[0])

#Result
sys.stdout.write("\nAscii Difference between two strings\n")
sys.stdout.write("Difference between (%s %s) = %d\n"%(a1,a2,c1))
sys.stdout.write("Difference between (%s %s) = %d\n"%(a3,a4,c2))
sys.stdout.write("Difference between (%s %s) = %d\n"%(a5,a6,c3))
Ascii Difference between two strings
Difference between (NAGPUR NAGPUR) = 0
Difference between (PANDHARPUR KOLHAPUR) = 5
Difference between (AURANGABAD HYDERABAD) = -7

Example 8.41, Page number: 272

In [37]:
#Sort city names alphabetically.

import sys

#Variable Initialization
city = [['0' for i in range(5)]for i in range(20)]
sys.stdout.write("Enter Names of Cities.  ")
for i in range(5):
    city[i] = raw_input("")
    
#Sorting & Result
sys.stdout.write("Sorted List of Cities.\n\n")
for i in range(65,122+1):
    for j in range(0,5):
        if ord(city[j][0]) == i:
            sys.stdout.write("\n%s"%(city[j]))
Enter Names of Cities.  MUMBAI
NANED
BANGLORE
KANPUR
INDORE
Sorted List of Cities.


BANGLORE
INDORE
KANPUR
MUMBAI
NANED

Example 8.42, Page number: 273

In [38]:
#Sort city names alphabetically

import sys

#Variable Initialization
city = [['0' for i in range(5)]for i in range(20)]
sys.stdout.write("Enter Names of Cities.  ")
for i in range(5):
    city[i] = raw_input("")
    
#Sorting & Result
sys.stdout.write("Sorted List of Cities.\n\n")
for i in range(0,5):
    for j in range(0,5):
        if city[j-1] > city[j]:
            temp = city[j-1]
            city[j-1] = city[j]
            city[j] = temp
            
for i in range(0,5):
    sys.stdout.write("\n%s"%(city[i]))
Enter Names of Cities.  MUMBAI
NANED
BANGLORE
KANPUR
INDORE
Sorted List of Cities.


BANGLORE
INDORE
KANPUR
MUMBAI
NANED

Example 8.43, Page number: 274

In [40]:
#Find number of words in a given statement.

import sys

#Variable Initialization
count = 1                #Counts the starting word
i = 0
text = raw_input("Enter The Line of Text\nGive One Space After Each Word")

#Calculation
while i < len(text):      #There is no null terminating character in python
    if ord(text[i]) == 32:
        count += 1
    i += 1
        
#Result
sys.stdout.write("\nThe Number of words in line = %d"%(count))
Enter The Line of Text
Give One Space After Each WordRead Books

The Number of words in line = 2

Example 8.44, Page number: 275

In [41]:
#Find number of words in a given statement.

import sys

#Variable Initialization
count = 0          
i = 0
text = raw_input("Enter Text Below :")

#Calculation
while i < len(text):     #There is no null terminating character in python for strings
    if ord(text[i]) >= 97 and ord(text[i]) <= 122 or ord(text[i]) >= 65 and ord(text[i]) <= 90:
        i += 1
        continue
    if ord(text[i]) == 32:
        count += 1
        i += 1
        continue

if i == len(text):
    count += 1
    
#Result
sys.stdout.write("The Number of words in line = %d"%(count))
    
Enter Text Below :Reading is a good Habit
The Number of words in line = 5

Example 8.45, Page number: 276

In [43]:
#Sort the last name of mobile customers alphabetically.

import sys

#Variable Initialization
fname = [['0' for i in range(20)] for i in range(10)]
sname = [['0' for i in range(20)] for i in range(10)]
surname = [['0' for i in range(20)] for i in range(10)]
name = [['0' for i in range(20)] for i in range(20)]
mobile = [['0' for i in range(20)] for i in range(10)]
temp = ['0' for i in range(20)]

sys.stdout.write("Enter First Name, Second Name, surname and Mobile Number ")
for i in range(0,5):
    fname[i] = raw_input("")
    sname[i] = raw_input("")
    surname[i] = raw_input("")
    mobile[i] = raw_input("")
    
    name[i] = surname[i] + " " 
    temp[0] = fname[i][0]
    name[i] = name[i] + temp[0] + "."
    temp[0] = sname[i][0]
    name[i] = name[i] + temp[0]
    
for i in range(0,5):
    for j in range(1,5-i):
        if name[j-1] > name[j]:
            temp = name[j-1]
            name[j-1] = name[j]
            name[j] = temp
            temp = mobile[j-1]
            mobile[j-1] = mobile[j]
            mobile[j] = temp
            
sys.stdout.write("List of Customers in alphanetical Order.")
for i in range(0,5):
    sys.stdout.write("\n%-20s\t %-10s\n"%(name[i],mobile[i]))
Enter First Name, Second Name, surname and Mobile Number K
S
MORE
458454
J
M
CHATE
658963
M
M
GORE
660585
L
K
JAIN
547855
J
J
JOSHI
354258
List of Customers in alphanetical Order.
CHATE J.M           	 658963    

GORE M.M            	 660585    

JAIN L.K            	 547855    

JOSHI J.J           	 354258    

MORE K.S            	 458454    
In [ ]: