Ticker

6/recent/ticker-posts

Python: 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"

Eg:
>>> ch='a'
>>> type(ch)
<class 'str'>

How to define multi-line String literals:

We can define multi-line String literals by using triple single or double quotes.

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:

We can access characters of a string by using the following ways.

1. By using index
2. By using slice operator

1. By using index:

Python supports both +ve and -ve index.
+ve index means left to right(Forward direction)
-ve index means right to left(Backward direction)

Eg:

s='durga'

diagram

Eg:

>>> s='durga'
>>> s[0]
'd'
>>> s[4]
'a'
>>> s[-1]
'a'
>>> s[10] 

IndexError: string index out of range

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:

1) s=input("Enter Some String:") 
2) i=0 
3) for x in s: 
4) print("The character present at positive index {} and at nEgative index {} is {}".format(i,i
-len(s),x)) 
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

2. Accessing characters by using slice operator:

Syntax: s[bEginindex:endindex:step]

bEginindex:From where we have to consider slice(substring)
endindex: We have to terminate the slice(substring) at endindex-1 
step: incremented value

Eg:

1) >>> s="Learning Python is very very easy!!!" 
2) >>> s[1:7:1] 
3) 'earnin' 
4) >>> s[1:7] 
5) 'earnin' 
6) >>> s[1:7:2] 
7) 'eri' 
8) >>> s[:7] 
9) 'Learnin' 
10) >>> s[7:] 
11) 'g Python is very very easy!!!' 
12) >>> s[::] 
13) 'Learning Python is very very easy!!!' 
14) >>> s[:] 
15) 'Learning Python is very very easy!!!' 
16) >>> s[::-1] 
17) '!!!ysae yrev yrev si nohtyP gninraeL' 

Behaviour of slice operator:

s[bEgin:end:step]

step value can be either +ve or –ve

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

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)

Mathematical Operators for String:

We can apply the following mathematical operators for Strings.

  1. + operator for concatenation
  2. * operator for repetition 

print("durga"+"soft") #durgasoft
print("durga"*2) #durgadurga

len() in-built function:

We can use len() function to find the number of characters present in the string.

Eg:
s='durga'
print(len(s)) #5

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:

1) s=input("Enter main string:") 
2) subs=input("Enter sub string:") 
3) if subs in s: 
4) print(subs,"is found in main string") 
5) else:
6) print(subs,"is not found in main string") 

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.

Comparison will be performed based on alphabetical order.

Eg:

1) s1=input("Enter first string:") 
2) s2=input("Enter Second string:") 
3) if s1==s2: 
4) print("Both strings are equal") 
5) elif s1<s2: 
6) print("First String is less than Second String") 
7) else: 
8) print("First String is greater than Second String") 

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

  1. rstrip()===>To remove spaces at right hand side
  2. lstrip()===>To remove spaces at left hand side
  3. strip() ==>To remove spaces both sides

Eg:

1) city=input("Enter your city Name:") 
2) scity=city.strip() 
3) if scity=='Hyderabad': 
4) print("Hello Hyderbadi..Adab") 
5) elif scity=='Chennai': 
6) print("Hello Madrasi...Vanakkam") 
7) elif scity=="Bangalore": 
8) print("Hello Kannadiga...Shubhodaya") 
9) else: 
10) print("your entered city is invalid") 

Finding Substrings:

We can use the following 4 methods

For forward direction:

find()
index()

For backward direction:

rfind()
rindex()

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:

1) s="Learning Python is very easy"
2) print(s.find("Python")) #9 
3) print(s.find("Java")) # -1 
4) print(s.find("r"))#3 
5) print(s.rfind("r"))#21 

s.find(substring, begin, end)

It will always search from begin index to end-1 index

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:

1) s=input("Enter main string:") 
2) subs=input("Enter sub string:") 
3) try: 
4) n=s.index(subs) 
5) except ValueError: 
6) print("substring not found") 
7) else: 
8) print("substring found") 

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

Counting substring in the given String:

We can find the number of occurrences of substring present in the given string by using count() method.

  1. s.count(substring) ==> It will search through out the string
  2. s.count(substring, bEgin, end) ===> It will search from bEgin index to end-1 index

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

Replacing a string with another string:

s.replace(oldstring,newstring)

inside s, every occurrence of oldstring will be replaced with newstring.

Eg1:

s="Learning Python is very difficult"
s1=s.replace("difficult","easy")
print(s1)

Output:

Learning Python is very easy

Eg2: All occurrences will be replaced

s="ababababababab"
s1=s.replace("a","b")
print(s1)

Output: bbbbbbbbbbbbbb

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:

1) s="durga software solutions" 
2) l=s.split() 
3) for x in l: 
4) print(x) 

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

Changing case of a String:

We can change case of a string by using the following 4 methods.

  1. upper()===>To convert all characters to upper case
  2. lower() ===>To convert all characters to lower case
  3. swapcase()===>converts all lower case characters to upper case and all upper case characters to lower case
  4. title() ===>To convert all character to title case. i.e first character in every word should be upper case and all remaining characters should be in lower case.
  5. capitalize() ==>Only first character will be converted to upper case and all remaining characters can be converted to lower case 

Eg:

s='learning Python is very Easy'
print(s.upper())
print(s.lower())
print(s.swapcase())
print(s.title())
print(s.capitalize())

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

Checking starting and ending part of the string:

Python contains the following methods for this purpose

  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

To check type of characters present in a string:

Python contains the following methods for this purpose.

1) isalnum(): Returns True if all characters are alphanumeric( a to z , A to Z ,0 to9 )
2) isalpha(): Returns True if all characters are only alphabet symbols(a to z,A to Z)
3) isdigit(): Returns True if all characters are digits only( 0 to 9)
4) islower(): Returns True if all characters are lower case alphabet symbols
5) isupper(): Returns True if all characters are upper case aplhabet symbols
6) istitle(): Returns True if string is in title case
7) isspace(): Returns True if string contains only spaces

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

Formatting the Strings:

We can format the strings with variable values by using replacement operator {} and format() method.

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

"Python String Data Type"

"Python String Data Type Size"

"Python String Data Type Numpy"

"In Python String Data Type Can Be Defined As"

"Change Data Type To String Python"

"How To Convert Object Data Type To String In Python"

"Check If Data Type Is String Python"

"Convert Data Type To String Python"