0% found this document useful (0 votes)
15 views28 pages

Chapter Py 5 Full

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)
15 views28 pages

Chapter Py 5 Full

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Chapter 5

Python Programs on Strings


5.1 Strings in Python

Strings in Python are created by enclosing them in double quotes. For example, “Hello”, “World”. The
enclosed quotes can be single or double.Example, ‘Hello’, ‘World’. There is no difference between strings
enclosed in single or double quotes.

Note: There is no char data type supported in Python.

5.2 Reading Strings from Keyboard

As we have seen earlier input ( ) helps to read a string from the keyboard.

Output:
5.3 Accessing Strings

To access strings in Python we can use index in square brackets.

Example:

Output:

Strings are indexed from 0 thus str_var [ 0 ] gives “ H ”. str_var [ -1 ] remains the last element “ o ”
and [ -2 ] returns the second last elements “ l ”. The str_var [ 4 ] is same as str_var [ -1 ].

Note: Single and double quoted strings in Python are identical

5.4 Modifying Strings in Python

Strings in Python are immutable. Once they have been created they cannot be modified.
Output:

5.5 String Concatenation

You can concatenate two strings by using the + operator. The plus operator takes the string on the left side
and clubs it with the string on the right side.

Example:

Output:

5.6 String Updating

You can update a string by creating a new string variable and then assigning the required substrings.

Example:
Output:

5.7 Finding the Length of a String

To find the length of a string you can use the built in method len ( ).

Syntax

Len ( string ) : returns the length of the string.

Example:

Output:

5.8 Iterating through a String

We can use a for loop or while loop to iterate through a string.

Example:
Output:

5.9 String Membership Operations

String Membership operations in Python is supported by two operators. This is given as follows.

 in: returns True if the character under test is in the given string else returns False.
 not in: returns True if the character under test is not in the given string else returns False.

Example:

Output:
5.10 Built-in String Functions

5.10.1 Converting Strings in Lowercase to uppercase, Vice Versa and Swapping the Case

 islower ( ): returns True if a given string has all lowercase letters else it returns False.

Syntax

Str.islower ()

 isupper ( ): returns True if a given string has all uppercase letters else it returns False.

Syntax

str.upper ( )

 lower ( ): converts all the uppercase letters of a given string to lowercase.

Syntax

Str.lower ( )

 upper ( ): converts all the lowercase letters of a given string to uppercase.

Syntax

Str.upper ( )

 swapcase ( ): reverts the case for all characters in a string. That is uppercase letters are converted to
lowercase and vice versa.

Syntax

Str.swapcase ( )

Example:
Output:

5.10.2 Searching in a String

 find( ): Tries to find if a substring occurs in a string for a given starting index beg and the ending
index as end (default beg = 0 and end = len (string). The function returns the index if the substring is
found or else returns – 1.
Syntax
str.find( ‘‘substring’’)
 index( ): Tries to find if a substring occurs in a string for a given starting index beg and the ending
index as end (default beg = 0and end = len (string). The function returns the index if the substring is
found or else raises and exception (i.e., similar to find ( ) function).
Syntax
str.index(‘‘substring’’)
 rfind( ): Works in a similar manner as find ( ) function but searches the substring in backward
direction.
Syntax
Str.rfind(‘‘substring’’)
 rindex( ): Works in a similar manner as index ( ) function but searches the substring in backward
direction.
Syntax
Str.rindex(‘‘substring’’)

Example:
Output:

5.10.3 Splitting Strings and Removing Whitespaces

 split( ): The Python split ( ) function breaks a string which is separated by a separator and returns a
list.
Syntax
str.split([sep, [maxsplit] ] )
 lstrip( ): The Python function lstrip ( ) removes all the leading whitespaces in a string and returns
the string minus leading whitespaces.
Syntax
str.lstrip ( )
 rstrip( ): The Python function rstrip ( ) removes the trailing whitespaces in a string and returns the
string minus trailing whitespaces.
Syntax
str.rstrip ( )
 strip( ): The strip ( ) function in Python removes the leading and trailing whitespaces. Essentially it
performs both lstrip ( ) and rstrip ( ) on a given string.
Syntax
str.strip ( [chars] )
where, chars is the characters to be removed from the beginning or end of the string.
 splitlines( ): Splits a given string by the newlines (\n) specified and return the string as a list with the
newlines removed.
Syntax
str.splitlines(num = str. Count(‘\n’)
If num which is an integer value and if included indicates the newlines need to be included in the
lines.
 isspace( ): The Python function isspace ( ) returns True if there is only whitespace characters in a
string like \ t etc., in a string or else it returns False.
Syntax
str.isspace ( )
Example: Python program to demonstrate built-in Python string functions for splitting strings and removing
whitespaces.

Output:

5.10.4 String Join, Length, Replace and Miscellaneous String Functions

 join( ): This function returns a string sequence joined by a string separator.


Syntax
separator.join ( str )
 len( ): This Python string function returns the length of the given string.
Syntax
len ( str )
 replace( ): This Python function replaces old occurrences of old string with the given new
replacement string and if count is specified then it replaces for the count number of occurrences.
Syntax
str.replace old, new[,count] )
The copy of the string is returned with new values updating the old ones.
 max( ): This Python string function returns the maximum alphabetical character in a string.
Syntax
max ( str )
 min( ): This Python string function returns the minimum alphabetical character in a string.
Syntax
min ( str )
 title( ): This Python string function converts a string in titled case with first character in uppercase
followed by lowercase letters.
Syntax
str.title ( )
 istitle( ): This Python string function checks whether a string is titled case and returns True else
returns False.
Syntax
str.istitle ( )
 capitalize( ): This Python string function capitalizes the first letter of the given string.
Syntax
str.capitalize ( )
Example: Python program to demonstrate string function for joining, finding length, replacing, etc.
Output:

5.11 Escape Sequences in Python

Escape sequence are characters that are preceded by a backslash\followed by a sequences of one or more
characters. Python supports the following escape sequence characters listed in Table 5.1.

Table 5.1 Escape Sequences in Python

Escape Sequence Description


\\ Blacklash \
\n Linefeed
\t Horizontal tab
\a Bell
\b Backspace
\f Form feed
\r Carriage return
\v Vertical Tab
\‘ Single Quote
\“ Double Quote

5.12 Write a Python Program to Check Whether an Entered String is a Palindrome or not without
using Built-in String Functions Available in Python

5.12.1 Theory
A string is said to be Palindrome whose characters when read backwards are same as the original string.
Example: a) malayalam c) mom
b) nun d) dad
5.12.2 Algorithm

Step 1: Start
Step 2: Read a string, input_string
Step 3: Initialize palin = True, length = 0
Step 4: for i in input_string repeat the following steps
Step 4.1: length = length + 1
Step 5: for i in range from 0 to length/2 repeat the following steps
Step 5.1: if input_string[i] == input_string[length-i-1]
Step 5.1.1: palin = True
Step 6: If plain == True:
Step 6.1: Write “Given String”, input_string, “Is a Palindrome”
Step 7: Else
Step 7.1: Write “Given String”, input_string, “Is not a Palindrome”
Step 8: Stop

5.12.3 Flowchart

Start

Read input_string

palin = True, length = 0

for i in input_string

length = length + 1

for I in range from 0 to length/2

False if input_string[i] ==
input_string[length-1-1]

True ↓

palin = True
if palin == False Write “Not a
True Palindrome”
True ↓

Write “Is a Palindrome”


Stop

5.12.4 Python Program: Palin.py

Output:

5.13 Write a Python Program to Count Separately the Vowels of a given String

5.13.1 Theory

Vowels: In phonetics a vowel is described as a speech sound with your tongue in the middle and not
touching your teeth or lips. In English alphabets the vowels are [a, e, i, o, u] and the rest are consonants [b, c,
d, f, g, h, j, k, l, m, n, p, q, r, s, t, v, w, x, y,z] out of the 26 letters.
5.13.2 Algorithm

Step 1: Start
Step 2: Read input_string in lowercase
Step 3: vowels = “aeiou”
Step 4: Flag = False
Step 5: for char in vowels repeat the following steps
Step 5.1: if char in input_string
Step 5.1.1: Write “Alphabet:”,char, input_string.count(char)
Step 5.1.2.: Flag = True
Step 6: if not Flag
Step 6.1: Write, “There are no vowels in:”, input_string
Step 7: Stop

5.13.3 Flowchart

Start

Read input_string

Vowels = “aeiou” Flag = False

for char in vowels repeat

False
if char in input_string

↓ True
Write char, count

Flag = True
↓ False
If not Flag
↓ True
Write “There are
no vowels”

Stop
5.13.4 Python Program: Vowel_count.py

Output:

5.14 Write a Python Program to Compute the Length of an Input String without using the Built-in
Python Function len()

5.14.1 Theory

The length of a string gives the number of characters in the string. This count is useful in for loops to
navigate up to the end of the string.

Example: input_string = “happy”

The length of the above string is 05

5.14.2 Algorithm

Step 1: Start
Step 2: Read the value for input_string
Step 3: Initialize value of count ← 0
Step 4: For char in input_string repeat the following steps
Step 4.1: count ← count + 1
Step 5: Write the length of string, count
Step 6: Stop
5.14.3 Flowchart

Start

Read input_string

count = 0

For char in input_string

count = count + 1

Write “Length:,”
count

Stop

5.14.4 Python Program: String_length.py

Output:

5.15 Write a Python Program to Count the Number of Characters in a given Word

5.15.1 Theory

The count of the characters in the string gives idea about how many characters of a given type are there in a
string.
Example: Enter a word: happy

Enter the character: p


The number of characters p in the given word happy is 2.

5.15.2 Algorithm

Step 1: Read input_word


Step 2: Read the character value, c
Step 3: count ← 0
Step 4: for ch in input_word repeat the following steps
Step 4.1: if c = ch
Step 4.1.1: count ← count + 1
Step 5: Write “The number of characters in given word”, count
Step 6: Stop

5.15.3 Flowchart

Start

Read input_word

Read c

count = 0

For ch in input_word

False
if c == ch

↓ True
count = count + 1

Write characters in a
given word, count

Stop
5.15.4 Python Program: Char_count.py

Output:

5.16 Write a Python Program to Check the Bigger of the Two Inputted Strings

15.16.1 Theory

Compute the length of the given two strings. If they are equal say so or print the largest among them.

Example: first_string = ‘ ‘ Hello ‘ ‘


Second_string = ‘ ‘ Happiness ‘ ‘
Length of first_string = ‘ ‘ Hello ‘ ‘ is 5
Length of second_string = ‘ ‘ Happiness ‘ ‘ is 9
Thus 9 > 5 and bigger among the two strings is
Second_string = ‘ ‘ Happiness ‘ ‘

5.16.2 Algorithm
Step 1: Start
Step 2: Read first_string
Step 3: Read second_string
Step 4: len-first ← 0, len_second ← o
Step 5: for char in first_string repeat the following steps
Step 5.1: len_first ← len_second + 1
Step 6: for char in second_string repeat the following steps
Step 6.1: len_second ← len_second + 1
Step 7: if len_first == len_second
Step 7.1: Write “The two strings are equal”
Step 8: if len_first > len_second
Step 8.1: Write “The first_string is bigger than second_string”
Step 9: else
Step 9.1: Write “The second_string is bigger than first_string
Step 10: Stop

5.16.3 Flowchart
Start

Read first_string

Read second_string

len_first = 0, len_second = 0

for char in first_string

len_first = len_first + 1

A

A

for char in second_string

len_second = len_second + 1

if len_first == True Write two strings


len_second are equal

False
if len_first > True Write first_string
len_second is bigger

False
Write second_string
is bigger

Stop
5.16.4 Python Program: Biggest_String.py

Output:

5.17 Write a Python Program to Count the Common Characters in the Two inputted Strings

5.17.1 Theory

Search the two strings for common characters. If they are found print them else state that there are no
common characters in the given strings.
Example: consider first_string = ‘ ‘ hello ‘ ‘ and second_string = ‘ ‘ hello ‘ ‘
The common characters are hello.

5.17.2 Python Program: Common_char.py

Output:

5.18 Write a Python Program to Count the occurrences of the Substring in a given String

5.18.1 Theory

A string S contains a substring s.


Example: String S = ‘ ‘ Everybody ‘ ‘. Then there is a substring s = ‘ ‘ body ‘ ‘

5.18.2 Algorithm

Step 1: Start
Step 2: Read “A given string”, string
Step 3: Read “A substring”, substring
Step 4: count ← 0, flag ← False
Step 5: len_sub ← len(substring)
Step 6: for I in range of len(substring) repeat the following steps
Step 6.1: if string [i: i + len_sub] == substring
Step 6.1.1: Flag ← True
Step 6.1.2: count ← count + 1
Step 7: if Flag
Step 7.1: Write substring is there,substring
Step 8: else
Step 8.1: Write substring is not found in the string
Step 6: Stop

5.18.3 Flowchart

Start

Read string

Read substring

count = 0, Flag = False, len_sub =
len(substring)

for i in range of len(substring)

False if string[i: i + len


sub==substring]

↓ True
flag = True, count = count + 1

False
if Flag Write “Substring is not
True found”,substring

Write “substring is
present”, substring

Stop
5.18.4 Python Program: Substring.py

Output:

5.19 Write a Python Program to Check Whether the Characters of an Inputted String are in
Alphabetical Order

5.19.1 Theory

The characters in a string are said to be in alphabetical order if they follow the alphabetical sequence of a, b,
c, d … w, x, y, z.

Example:
i. “hello”
Here h comes before e and hence the above string is not in alphabetical order.
ii. “or”
Here the character o comes before r in the alphabetical sequence and thus follows the order.
5.19.2 Algorithm

Step 1: Read the given string, input_string


Step 2: Flag ← True
Step 3: for i in range(0, len(input_string) – 1)) repeat the following steps:
Step 3.1: if input_string[i] > input_string[i +1]
Step 3.1.1: Flag ← False
Step 4: if Flag == True
Step 4.1: Write the characters in the string are in alphabetical order
Step 5: else
Step 5.1: Write the characters in string are not in alphabetical order
Step 6: Stop

5.19.3 Flowchart

Start

Read input_string

Flag = True

for i in range(0, len(input_string) – 1)

False if input_string[i] >


input_string[I +1]

↓ True
Flag = False

False
if flag == True Write the characters are
not in alphabetical order

↓ True
Write the characters are
in alphabetical order

Stop
5.19.4 Python Program: Alpha_String.py

Output:

5.20 Write a Python Program to Sort Words Entered by User in Alphabetical Order

5.20.1 Theory

The Bubble sort iterates through multiple passes over a list of elements. The adjacent elements are compared
and if they are not in order they are exchanged. In the first pass the the highest element goes to the highest
index. Thus after making n – 1 passes the smallest element will be there in the first position and the list will
be sorted. Also in each pass the number of comparisons goes on redudcing.

Example consider the following words “ raju” , “mohan”, “brijesh”, “sachin”, “virat”
Pass 1:
(i) “raju” is greater than “mohan”
“mohan”, “raju”, “brijesh”, “sachin”, “virat”
(ii) “raju” is greater than “brijesh”
“mohan”, “brijesh”, “raju”, “sachin”, “virat”
(iii) “raju” not greater than “sachin”
“mohan”, “brijesh”, “raju”, “sachin”, “virat”
(iv) “sachin” not greater than “virat”
“mohan”, “brijesh”, “raju”, “sachin”, “virat”
Pass 2:
(i) “mohan” is greater than “brijesh”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”
(ii) “mohan” is not greater than “raju”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”
(iii) “raju” is not greater than “sachin”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”
Pass 3:
(i) “brijesh” is not greater than “mohan”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”
(ii) “mohan” is not greater than “raju”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”
Pass 4:
(i) “brijesh” is not greater than “mohan”
“brijesh”, “mohan”, “raju”, “sachin”, “virat”

5.20.2 Algorithm

Step 1: Start
Step 2: Enter the number of words to be sorted, n
Step 3: words ← list ( )
Step 4: Write “Enter the words”
Step 5: for i in range len(words) repeat the following steps
Step 5.1: read the words, words[i]
Step 5.2: temp = “ ”
Step 6: for i in range len(words) repeat the following steps
Step 6.1: for j in range of len(words) – 1 – i
Step 6.1.1: if words[j] > words[j + 1]
Step 6.1.1.1: temp = words[j]
Step 6.1.1.2: words[j] = words[j + 1]
Step 6.1.1.3: words[j + 1] = temp
Step 7: Write “The sorted words are”
Step 7.1: for i in range len(words)
Step 7.1.1: Write, words[i]
Step 8: Stop
5.20.3 Flowchart

Start

Enter the number of words, n

words = list()

Write “Enter the words”

for i in range(0, n)

read the words, temp = “ ”
words [i]

for i in range len(words)

for i in range of len(words) – 1 – 1

False
if words[j] > words[j + 1]

↓ True
temp = words[j]; words =
words[j + 1]; words[j + 1} = temp

for i in range len(words)

Write, words[i]

Stop

5.20.4 Python Program: Sort_String.py


Output:

You might also like