Sequential Data Type : String1
A string is a sequence of one or more characters (letters, numbers, symbols) that can be either a con-
stant or a variable.
String has following characteristics:
1- Values in Strings are stored in forms of Sequence like.
str=’Rajesh’
Contents=> R a j e s h
Index=> 0 1 2 3 4 5
2- Strings in Python are immutable (Non changeable) data type.
3- Strings in Python are stored by using:
(a) Single Quotes.
x=’Shiv’
(b) Double Quotes.
x=”Shiv”
(c) Triple Quotes: Multi line strings can be stored by using this.
x=’’’once upon
a time there
was a king.’’’
LOGICAL AND PHYSICAL LINES
A physical line is what you see when you write the program. A logical line is what Python sees as a single
statement.
If you have a long line of code, you can break it into multiple physical lines by using the backslash (\) The
backslash in the string makes the string continue on the next line without a newline. This is referred to
as explicit line joining. For example,
s = 'This is First Line, \
This is simple string.'
print(s)
Will print : - This is first line, This is simple string.
Note That you can also print the special characters like Single quotes ‘ , double quotes “ and , comma
, using \ .
Suppose you have t print :
I said him, “you can’t reach timely.”
print(“I said,”you can’t reach timely.””)
Write the statement like this:
print("I said him, \"You can't reach timely\". ")
20,000 - 10 inch
Working with String:
When we store a string value inside a variable,
str=”MOHANDAS”
it will access like this:
str M O H A N D A S
POSITIVE 0 1 2 3 4 5 6 7
INDEX
NEGATIVE -8 -7 -6 -5 -4 -3 -2 -1
INDEX
Now we can check the contents of str using:
print(str[2]) -H
print(str[-2]) -A
We can also add two string using + (Concatenation)
Eg:
str1=”suraj”
str2=”singh”
str3=str1+str2
print(str3) - surajsingh
len(): This function is used to get the length of given string.
str=’mohan’
l=len(str)
print(l) -5
Traversal Inside String:
Using Loop we can also check the position of all the elements stored inside the string variable.
st=input("Enter the String:")
l=len(st)
for x in range(0,l,1):
print(st[x])
OR
st=input("Enter the String:")
for i in st:
print(i)
You have been always know that var i has every time worked like an integer variable, But here
is surprising that var i will automatically adjust according to st var.
Note That here i is a variable that will automatically adjust according to string contents. Here
i variable will work like a character that will passes for each chars in st (i.e. String variable).
We can also print the given string in reverse order.
st=input("Enter the String:")
l=len(st)
for x in range(l-1,-1,-1):
print(st[x])
# WAP to check whether a given char is found inside string.
s1=input("Enter the String:")
s2=input("Enter a char to search:")
t=0
l=len(s1)
for x in range(0,l,1):
if(s1[x]==s2):
t=1
break
if(t==1):
print("Give char is Found:")
else:
print("Give char is Not Found:")
# WAP to check whether print the frequency of a char in given string.
s1=input("Enter the String:")
s2=input("Enter a char to search:")
t=0
l=len(s1)
for x in range(0,l,1):
if(s1[x]==s2):
t=t+1
if(t>=1):
print("Give char is Found:",t)
else:
print("Give char is Not Found:")
String formatting:
format () : The format() is one of the string formatting methods in Python, which allows multiple
substitutions and value formatting. Format string contains curly braces {} as placeholders or
replacement fields which get replaced. (File-s10)
str1 = "{}{}{}".format('Old', 'is', 'Gold')
print ("String in default order: ")
print(str1)
str1 = "{1}{0}{2}".format('Old', 'is', 'Gold')
print ("String according to positional order: ")
print(str1)
str1 = "{i}{g}{o}".format(o='Old', i='is', g='Gold')
print ("String according to keyword order: ")
print(str1)
Program for Palindrome: A String is a palindrome, when forward and reverse is same.
For eg: kanak, malayalam are palindrome string.
From Left to Right (var x)
k a n a m
From Right to Left (var lastindex)
Solution:
st=input("Enter the Input:")
l=len(st)
t=0
lastindex=l-1
x=0
while(x<l):
if(st[x]!=st[lastindex]):
t=1
break
x=x+1
lastindex=lastindex-1
if(t==0):
print("String is Palindrome")
else:
print("String is Not Palindrome")
Special String Operators:
Concatenation (+) Operator:
The + is a operator, that is used as concatenation to join the strings.
For eg:
>>> ‘Shiv’+’Myedutech’
Output : ShivMyedutech
Note :that 5+5 is valid , ‘5’+’5’ is also valid , while ‘5’+5 is invalid.
Replication (*) Operator:
The * is a operator, that is used to replicate the strings up to given number of times.
For eg:
>>> s1=’Rajesh
>>> s1*5
Membership (in) Operator:
The membership operator in returns True if given character is available in string otherwise False.
Eg:
>>>st=”Old is Gold”
>>> ‘G’ in st Returns True
Note that we can compare the string using “abc”==”Abc”, it will return False, because comparison
will made according toASCII code of string.
Membership (not in) Operator:
This is exactly opposite to in.
>>>st=”Old is Gold”
>>> ‘G’ not in st Returns False
Note that we can compare the string using “abc”==”Abc”, it will return False, because comparison
will made according toASCII code of string.
Comparison Operator:
All the comparison operators (<,>,>=,<=) are also applied on string for comparison. String can be
compared to their corresponding ASCII values.
For eg:
ASCII Code
A - Z = 65 to 90
a - z = 97 to 122
0 -9 = 48 to 57
Ord(): Ord() returns the ordinal value of a single character.
Eg:
>>> ord (‘A’) - 65
chr(): Chr() converts the given ASCII value into corresponding character.
Eg:
>>> chr (65) A
String Slices:-
Using Slicing is a mechanism by which we can get range of items from sequence. You can retrieve a slice
(sub- string) of a string with a slice operation. The slicing operation is used by specifying the name of the
sequence followed by an optional pair of numbers separated by a colon enclosed within [](square
brackets). The slice operator [] is used to access the individual characters of the string. However, you can
use the: (colon) operator in Python to access the substring.
Consider with following example:
str D E E P A L I
POSITIVE 0 1 2 3 4 5 6
INDEX
NEGATIVE -7 -6 -5 -4 -3 -2 -1
INDEX
my_str = 'DEEPALI'
print('Chars 1 to 3 is', my_str [1:3])# EE
print('Chars 2 to end is', my_str [2:])# EPALI
print('Chars 1 to -1 is', my_str [1:-1]) # EEPAL
print('Chars 0 to -1 is', my_str [:-1]) # DEEPAL
print('Chars -7 to -2 is', my_str[-7:-2]) # DEEPA
print('Chars -5 to -4 is', my_str [-5:-4]) # E
print('Chars start to end is', my_str[:]) # DEEPALI
print('characters start to end is', my_str[:]) DEEPALI
String Functions and Methods:
len(): This method is used get the length of input string.
=len(‘Amit) -4
find():The find() method is used to identify the position of the given substring within the string, it
returns -1 if it is not found inside the string.
find (str, beg=0 end-len (string))
>>> str= "Once upon a time."
>>> [Link]('pan') Result will be -1
In other words, it returns -1 because substring is not found in the given string. On ignoring the
start parameter, the function starts the searching process from the very beginning.
>>> [Link]('up') Result will be 5
>>> [Link]('on',4,16) Result will be 8
isalnum(): It reurns true when a string has only alphanumeric keys except special chars.
Eg:
str1='sunara34'
[Link]()
True
str1='sundar34$'
[Link]()
False
isalpha(): It returns true when a string has only alphabetic chars except special chars and
numeric digits.
Eg:
str1='shyam45'
[Link]()
False
str1='shyam'
[Link]()
True
isdigit(): It returns true when a string has only numeric digits except special chars and alpha.
Eg:
str1='235'
[Link]()
True
str1='899k'
[Link]()
False
lower(): It converts the given string into lower case.
Eg:
s1='MyEdutech'
[Link]()
'myedutech'
islower():- This function checks case (upper or lower) of the given string, if passed argument is
lower caser it returns true otherwise false.
Eg:
s1='MyEdutech'
[Link]()
False
s1='myedutech'
[Link]()
True
isupper():- This function checks case (upper or lower) of the given string, if passed argument is
upper caser it returns true otherwise false.
Eg:
s1='MYEDUTECH'
[Link]()
True
s1='myedutech'
[Link]()
False
upper(): It converts the given string into upper case.
Eg:
s1='MyEdutech'
[Link]()
MYEDUTECH
lstrip(): It removes all the leading whitespaces from left side of given string.
s1=’ myedutech’
[Link]()
myedutech
It can also remove the characters from left side as it matches.
s1=’myedutech’
[Link](‘my’)
‘edutech’
rstrip(): It removes all the leading whitespaces from right side of given string.
s1=’myedutech ’
[Link]()
‘myedutech ’
It can also remove the characters from left side as it matches.
s1=’myedutech’
[Link](‘tech’)
‘myedu’
issapce(): It return true if string contains only whitespace in string otherwise false.
>>>s1=’shiv dutta ’
>>>[Link]()
False
>>>’ ‘.isspace()
True
istitle(): It return true if string contains will be passed as Title Case(First char of each Word is in
Title case) otherwise False.
>>>s1=’My name Is Shiv’
>>>[Link]()
False
>>>s1=’My Name Is Shiv’
>>>[Link]()
True
replace(): It replaces the string with all occurrences via given second substring.
s1='a quick brown fox jumped'
[Link]('quick','slow')
'a slow brown fox jumped'
Another example:
s1=''This is a good toy."
[Link]('is' ,'was')
'Thwas was a good toy'
split(): This function returns the given string in separated form as per space in given string.
s1='ram is a good boy'
s2=[Link]()
print(s2)
['ram', 'is', 'a', 'good', 'boy']
join() :- This function joins/combines the given separate string into a single string variable.
s1={'mohan','das','karam','chand'}
s2=' '
[Link](s1)
'mohan karam das chand'
swapcase(): - This function changes the case (either from upper case to lowercase or vice
versa.
Eg:1
s1='myedutech'
[Link]()
'MYEDUTECH'
Eg:2
s1='MYEDUTECH'
[Link]()
'myedutech'
partition(): - This function divides the given string in 3 parts as first given sub string.
Eg:
s1='old is gold'
[Link]('is')
('old ', 'is', ' gold')
The above string will divided into 3 parts as per given to partition().
str(): - This function converts the given argument of numeric type into string.
Eg:
x=12
y=str(x)
print(y)
‘12’