10. String Data Type
10. String Data Type
The most commonly used object in any project and in any programming language is String only.
Hence we should aware complete information about String data type.
What is String?
Any sequence of characters within either single quotes or double quotes is considered as a
String.
Syntax:
s='durga'
s="durga"
Note: In most of other languges like C, C++,Java, a single character with in single quotes is
treated as char data type value. But in Python we are not having char data type.Hence it is
treated as String only.
Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>
Eg:
>>> s='''durga
software
solutions'''
We can also use triple quotes to use single quotes or double quotes as symbol inside String
literal.
Eg:
s='This is ' single quote symbol'
==>invalid s='This is \' single quote
symbol' ==>valid s="This is ' single quote
symbol"====>valid s='This is " double
quotes symbol' ==>valid
s='The "Python Notes" by 'durga' is very helpful' ==>invalid
s="The "Python Notes" by 'durga' is very helpful"==>invalid
s='The \"Python Notes\" by \'durga\' is very helpful' ==>valid
s='''The "Python Notes" by 'durga' is very helpful''' ==>valid
How to access characters of a String:
1. By using index
2. By using slice operator
1. By using index:
Eg:
s='durga'
diagram
Eg:
>>> s='durga'
>>> s[0]
'd'
>>> s[4]
'a'
>>> s[-1]
'a'
>>> s[10]
IndexError: string index out of range
Note: If we are trying to access characters of a string with out of range index then we
will get error saying : IndexError
Q. Write a program to accept some string from the keyboard and display its characters by
index wise(both positive and nEgative index)
test.py:
5) i=i+1
Output: D:\
python_classes>py test.py
Enter Some String:durga
The character present at positive index 0 and at nEgative index -5
is d The character present at positive index 1 and at nEgative index
-4 is u The character present at positive index 2 and at nEgative
index -3 is r The character present at positive index 3 and at
nEgative index -2 is g The character present at positive index 4 and
at nEgative index -1 is a
Syntax: s[bEginindex:endindex:step]
Note: If we are not specifying bEgin index then it will consider from bEginning of the
string. If we are not specifying end index then it will consider up to end of the
string
The default value for step is 1
Eg:
5) 'earnin'
6) >>> s[1:7:2]
7) 'eri'
9) 'Learnin'
10) >>> s[7:]
11) 'g Python is very very easy!!!'
if +ve then it should be forward direction(left to right) and we have to consider bEgin to
end-1 if -ve then it should be backward direction(right to left) and we have to consider bEgin
to end+1
***Note:
In the backward direction if end value is -1 then result is always
empty. In the forward direction if end value is 0 then result is
always empty.
In forward direction:
default value for bEgin: 0
default value for end: length of
string default value for step: +1
In backward direction:
default value for bEgin: -1
default value for end: -(length of string+1)
Note: Either forward or backward direction, we can take both +ve and -ve values for bEgin
and end index.
print("durga"+"soft") #durgasoft
print("durga"*2) #durgadurga
Note:
1. To use + operator for Strings, compulsory both arguments should be str type
2. To use * operator for Strings, compulsory one argument should be str and other
argument should be int
Eg:
s='durga'
print(len(s)) #5
Q. Write a program to access each character of string in forward and backward
direction by using while loop?
Alternative ways:
1) s="Learning Python is very easy !!!"
2) print("Forward direction")
3) for i in s:
4) print(i,end=' ')
5)
6) print("Forward direction")
7) for i in s[::]:
8) print(i,end=' ')
9)
10) print("Backward direction")
11) for i in s[::-1]:
12) print(i,end=' ')
Checking Membership:
We can check whether the character or string is the member of another string or not by using in
and not in operators
s='durga'
print('d' in s) #True
print('z' in s) #False
Program:
Output:
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:durga
durga is found in main string
D:\python_classes>py test.py
Enter main string:durgasoftwaresolutions
Enter sub string:python
python is not found in main string
Comparison of Strings:
We can use comparison operators (<,<=,>,>=) and equality operators(==,!=) for strings.
Eg:
Output: D:\
python_classes>py test.py
Enter first string:durga
Enter Second string:durga
Both strings are equal
D:\python_classes>py test.py
Enter first string:durga
Enter Second string:ravi
First String is less than Second String
D:\python_classes>py test.py
Enter first string:durga
Enter Second string:anil
First String is greater than Second String
Removing spaces from the string:
We can use the following 3 methods
Eg:
Finding Substrings:
We can use the following 4 methods
1. find():
s.find(substring)
Returns index of first occurrence of the given substring. If it is not available then we will get -
1
Eg:
Note: By default find() method can search total string. We can also specify the boundaries to
search.
s.find(substring,bEgin,end)
Eg:
1) s="durgaravipavanshiva"
2) print(s.find('a'))#4
3) print(s.find('a',7,15))#10
4) print(s.find('z',7,15))#-1
index() method:
index() method is exactly same as find() method except that if the specified substring is
not available then we will get ValueError.
Eg:
Output:
D:\python_classes>py test.py
Enter main string:learning python is very
easy Enter sub string:python
substring found
D:\python_classes>py test.py
Enter main string:learning python is very
easy Enter sub string:java
substring not found
Q. Program to display all positions of substring in a given main string
5) n=len(s)
6) while True:
7) pos=s.find(subs,pos+1,n)
9) break
10) print("Found at position",pos)
11) flag=True
Output:
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:a
Found at position
0 Found at
position 3 Found
at position 5
Found at position
7 Found at
position 9 Found
at position 11
D:\python_classes>py test.py
Enter main string:abbababababacdefg
Enter sub string:bb
Found at position 1
Eg:
1) s="abcabcabcabcadda"
2) print(s.count('a'))
3) print(s.count('ab'))
4) print(s.count('a',3,7))
Output:
6
4
2
Eg1:
s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)
Output:
Learning Python is very easy
s="ababababababab"
s1=s.replace("a","b")
print(s1)
Output: bbbbbbbbbbbbbb
Q. String objects are immutable then how we can change the content by
using replace() method.
Once we creates string object, we cannot change the content.This non changeable behaviour
is nothing but immutability. If we are trying to change the content by using any method,
then with those changes a new object will be created and changes won't be happend in
existing object.
Hence with replace() method also a new object got created but existing object won't be
changed.
Eg:
s="abab"
s1=s.replace("a","b")
print(s,"is available at :",id(s))
print(s1,"is available at :",id(s1))
Output:
abab is available at :
4568672 bbbb is available at
: 4568704
In the above example, original object is available and we can see new object which was created
because of replace() method.
Splitting of Strings:
We can split the given string according to specified seperator by using split() method.
l=s.split(seperator)
The default seperator is space. The return type of split() method is List
Eg1:
Output:
durga
software
solutions
Eg2:
1) s="22-02-2018"
2) l=s.split('-')
3) for x in l:
4) print(x)
Output:
22
02
2018
Joining of Strings:
We can join a group of strings(list or tuple) wrt the given seperator.
s=seperator.join(group of strings)
Eg:
t=('sunny','bunny','chinny')
s='-'.join(t)
print(s)
Output: sunny-bunny-chinny
Eg2:
l=['hyderabad','singapore','london','dubai']
s=':'.join(l)
print(s)
hyderabad:singapore:london:dubai
Eg:
s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())
print(s)
Output:
LEARNING PYTHON IS VERY EASY
learning python is very easy
LEARNING pYTHON IS VERY
eASY
Learning Python Is Very
Easy Learning python is
very easy
1. s.startswith(substring)
2. s.endswith(substring)
Eg:
s='learning Python is very
easy'
print(s.startswith('learning'))
print(s.endswith('learning'))
print(s.endswith('easy'))
Output:
True
False
True
Eg:
print('Durga786'.isalnum()) #True
print('durga786'.isalpha()) #False
print('durga'.isalpha()) #True
print('durga'.isdigit()) #False
print('786786'.isdigit()) #True
print('abc'.islower()) #True
print('Abc'.islower()) #False
print('abc123'.islower()) #True
print('ABC'.isupper()) #True
print('Learning python is Easy'.istitle()) #False
print('Learning Python Is Easy'.istitle())
#True print(' '.isspace()) #True
Demo Program:
D:\python_classes>py test.py
Enter any character:7
Alpha Numeric Character
it is a digit
D:\python_classes>py test.py
Enter any character:a
Alpha Numeric Character
Alphabet character
Lower case alphabet character
D:\python_classes>py test.py
Enter any character:$
Non Space Special Character
D:\python_classes>py test.py
Enter any character:A
Alpha Numeric Character
Alphabet character
Upper case alphabet character
Eg:
name='durga'
salary=10000
age=48
print("{} 's salary is {} and his age is {}".format(name,salary,age))
print("{0} 's salary is {1} and his age is {2}".format(name,salary,age))
print("{x} 's salary is {y} and his age is
{z}".format(z=age,y=salary,x=name))
Output:
durga 's salary is 10000 and his age is
48 durga 's salary is 10000 and his age
is 48 durga 's salary is 10000 and his
age is 48