Strings
Strings
String is basically the sequence of characters. Any desired character can be accessed using
the index.
Strings
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.
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 +.
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
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.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.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
>>>