Problem Solving and Python Programming: UNIT III: Control Flow, Functions, Strings

Strings

Syntax, Example Program | Python Programming

String is basically the sequence of characters. Any desired character can be accessed using the index.

Strings    AU : May-19, Dec.-19, Marks 8

String is basically the sequence of characters.

Any desired character can be accessed using the index.

For example >>> country ="India"

>>> country[1] → Here using index the particular character is accessed

'n'

>>> country[2]

'd'

>>> 

The index is an integer value if it is a decimal value, then it will raise an error. For example

>>> country(1.5)

TypeError: string indices must be integers

>>> The string can be created using double quote or single quotes. For example

>>> msg="Hello"

>>> print(msg)

Hello

>>> msg ='Goodbye'

>>> print(msg)

Goodbye

Finding length of a String

There is an in-built function to find length of the string. This is len function. For example

>>> msg="Goodbye'

>>> print(msg)

Goodbye

>>> len(msg)

7

Traversing the String

We can traverse the string using the for loop or using while loop.

Example 1 - Traversing a string using while string


Example 2 - The string can be traversed using for loop

Python Program

msg = 'GoodBye'

for index in range(0, len(msg)):

letter = msg[index]

print(letter)

index = index + 1

Output

G

o

o

d

B

y

e

>>> 

 

Example 3.8.1 Write a program to display a set of strings using range() function.

AU : Dec.-19, Marks 2

Solution :

handsets = ['Samsung', 'OPPO', 'OnePlus', 'Apple')

print("The mobile handsets are...")

for i in range(len(handsets)):

print(handsets[i], end ="")

Output

The mobile handsets are...

Samsung OPPO OnePlus Apple

>>> 

 

1. String Slices

String slice is an extracted chunk of characters from the original string. In python we can obtain the string slice with the help of string indices. For example - We can obtain

>>> msg = "Good Morning"

>>> msg[0:4]

'Good' >>> msg(5:12]

'Morning'

Here the string from 0 to less than 4 index will be displayed. In the next command the string from 5th index to 11th index is displayed.


Fig. 3.8.1 string slice

We can omit the beginning index. In that case, the beginning index is considered as 0. For example

>>> msg[:4] ←Here the starting index will be 0

'Good'

Similarly we can omit ending index. In that case, the string will be displayed upto its ending character. For example -

>>> msg[5:] ← Here the last character of the string is the ending index

Morning

>>> 

If we do not specify any starting index or ending index then the string from starting index 0 to ending index as last character position will be considered and the entire string will be displayed. For example

>>> msg[:]

Good Morning

>>> 

 

2. Immutability

Strings are immutable i.e we cannot change the existing strings. For example

>>> msg = "Good Morning"

>>> msg[0]='g'

Output

TypeError: 'str' object does not support item assignment

To make the desired changes we need to take new string and manipulate it as per our requirement. Here is an illustration

Python Program

msg = 'Good Morning'

new_msg = 'g'+ msg[1:]

print(new_msg)


Program Explanation :

In above example the new_msg string is created to display "good morning" instead of “Good Morning"

The string slice from character 1 to end of string is concatenated with the character'g'. The concatenation is performed using the operator +.

 

3. String Functions and Methods

In this section we will discuss various string functions and methods.

1. String Concatenation

Joining of two or more strings is called concatenation.

In python we use + operator for concatenation of two strings.

For example –


2. String Comparison

The string comparison can be done using the relational operators like <,>,= = . For example

>>> msg1="aaa"

>>> msg2="aaa"

>>> msg1= =msg2

True

>>> msg1="aaa"

>>> msg2="bbb"

>>>print(msg1<msg2)

True

Note that, the string comparison is made based on alphabetical ordering. All the upper case letters appear before all the lower case letters.

3. String Repetition

We can repeat the string using * operator. For example

>>> msg="Welcome!"

>>> print(msg*3)

Welcome!Welcome!Welcome!

4. Membership Test

The membership of particular character is determined using the keyword in. For example -

>>> msg ="Welcome"

>>> 'm' in msg

True

>>> 't' in msg

False

>>> 

Methods in String Manipulation

Some commonly used methods are enlisted in the following table.

Method : count ()

Purpose : This methods searches the substring and returns how many times the substring is present in it.

Method : capitalize()

Purpose : This function returns a string with first letter capitalized. It doesn't modify the old string

Method : find()

Purpose : The find() method returns the lowest index of the substring (if found). If not found, it returns - 1.

Method : index

Purpose : This method returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.

Method : isalnum().

Purpose : The isalnum() method returns True if all characters in the string are alphanumeric

Method :  isdigit()

Purpose : The isdigit() method returns True it all characters in a string are digits. If not, it returns False

Method : islower()

Purpose : The islower() method returns True if all alphabets in a string are lowercase alphabets. If the string contains at least one uppercase alphabet, it returns False

Let us illustrate these methods with the help of python code.


 

4.  String Module

The string module contains number of constants and functions to process the strings. To use the string module in the python program we need to import it at the beginning.

Functions

We will discuss, some useful function used in string module.

1. The capwords function to display first letter capital

The capwords is a function that converts first letter of the string into capital letter.

Syntax

string.capwords(string)

Example program : Following is a simple python program in which the first character of each word in the string is converted to capital letter.

stringDemo.py

import string

str = 'i love python programming'

print(str)

print(string.capwords(str))

Output


2. The upper function and lower case

For converting the given string into upper case letter. We have to use str.uppr() function instead of string.upper. Similarly str.lower() function is for converting the string into lower case. Following program illustrates this.

StringDemo1.py

import string

text1 = 'i love programming'

text2 = 'PROGRAMMING IN PYTHON IS REALLY INTERESTING'

print("Original String: "text1)

print("String in Upper Case: ",str.upper(text1))

print("Original String: "text2)

print("String in Lower Case: ",str.lower(text2))

Output

Original String: i love programming

String in Upper Case: I LOVE PROGRAMMING

Original String: PROGRAMMING IN PYTHON IS REALLY INTERESTING

String in Lower Case: programming in python is really interesting

>>>

3. Translation of character to other form.

The maketrans() returns the translation table for passing to translate(), that will map each character in from_ch into the character at the same position in to_ch. The from_ch and to_ch must have the same length.

Syntax

string.maketrans(from_ch, to_ch)

Programming Example

Stringmodule2.py

from_ch = "aeo"

to_ch = "012"

new_str = str.maketrans(from_ch,to_ch)

str = "I love programming in python"

print(str) print (str.translate(new_str))

Output

I love programming in python

I 12v1 pr2gromming in pyth2n

Program explanation : In above program,

1) We have generated a translation table for the characters a, e and o characters. These characters will be mapped to 0, 1 and 2 respectively using the function maketrans.

2) The actual conversion of the given string will take place using the function translate.

3) According the above programming example, the string “I Love Programming in Python” is taken. From this string we locate the letters a, e and o, these letters will be replaced by 0, 1 and 2 respectively.

 4) The resultant string will then be displayed on the console.

Constants

Various constants defined in string module are -


We can display the values of these string constants in python program. For example -

ConstantDemo.py


 

5. Programming Examples Based on String

Example 3.8.2 Write a Python program to find the length of a string

Solution :

def str_length(str):

len = 0

for ch in str:

len + = 1

return len

print(“\t\t Program to find the length of a string”)

print(“Enter some string:”)

str = input()

print(“Length of a string is: “,str_length(str))

Output

Program to find the length of a string

Enter some string:

Python

Length of a string is : 6

>>> 

 

Example 3.8.2 Write a Python program to count occurrence of each word in given sentence.

Solution :

def count_occur(str):

data = dict()

words=str.split()

for word in words:

if word in data:

data(word]+ = 1

else:

data[word]=1

return data

print("Enter some string:")

str = input()

print(count_occur(str))

Output

Enter some string :

A big black bear sat on a big black rug

{'A': 1, 'big': 2, 'black': 2, 'bear': 1, 'sat': 1, 'on': 1, 'a': 1, 'rug': 1}

>>> 

 

Example 3.8.4 Write a Python program to copy one string to another.

Solution : print("Enter some string:")

str1=input()

str2="

for i in range (len(str1)):

str2=str2+str1[i]

print("The copied string is: ".str2)

Output

Enter some string:

Technical

moitulo The copied string is: Technical

>>>

 

Example 3.8.5 Write a Python program to check if a substring is present in the given string or not.

Solution : print("Enter some string: ")

str1=input().

print("Enter a word: ")

str2=input()

if(str1.find(str2)= =-1):

print("The substring ",str2," is not present in ",str1)

else:

print("The substring",str2," is present in ",str1)

Output

Enter some string:

sky blue

Enter a word:

blue The substring blue is present in sky blue

>>> 

 

Example 3.8.6 Write a Python program to count number of digits and letters in a string,

Solution :

print("Enter some string: ")

str = input()

digit_count = 0

letter_count = 0

for i in str:

if(i.isdigit());

digit_count + = 1

else:

letter_count + = 1

print("Total number of digits in ",str," are ", digit_count)

print("Total number of letters in ",str," are ",letter_count)

Output

Enter some string :

Python123Program

Total number of digits in Python123Program are 3

Total number of letters in Python123Program are 13

>>>

 

Example 3.8.7 Write a Python program to count number of vowels in a string,

Solution :

print("Enter some string: ")

str = input()

vowel_count = 0

for i in str:

if((i= ='a' or i= ='e' or i= ='i' or i= ='o' or i= ='u')

or((i= ='A' or i= ='E' or i= ='I' or i= ='0' or i=='U'))):

vowel_count+=1

print("Total number of vowels in ",str," are ",vowel_count)

Output

Enter some string:

India

Total number of vowels in India are 3

>>>

 

Example 3.8.8 Write a Python program to check if the string is palindrome or not.

Solution :

print("Enter some string:")

str = input()

rev_str = reversed(str)

if(list(str) = = list(rev_str));

print("The string",str," is palindrome ")

else

print("The string ",str," is not palindrome")

Output

Enter some string :

madam

The string madam is palindrome

>>>

 

Example 3.8.9 Write a Python program to sort the word in a sentence in an alphabetic order.

 Solution :

print("Enter some string: ")

str = input()

words_list = str.split()

words_list.sort()

print("The words in sorted order are...")

for word in words_list:

print(word)

Output

Enter some string :

I like python program very much

The words in sorted order are...

I

Like

much

program

python

very

>>> 

Review Questions

1. Analyse the string slicing. Illustrate how it is done in Python with example.

AU : May-19, Marks 8

2. Write a Python code to search a string in the given list.

AU : May-19, Marks 8

3. Python strings are immutable. Justify with an example.

AU : Dec.-19, Marks 8

 

Problem Solving and Python Programming: UNIT III: Control Flow, Functions, Strings : Tag: Engineering Python : Syntax, Example Program | Python Programming - Strings