Nothing Special   »   [go: up one dir, main page]

String

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

STRING :

A digit or a letter or a symbol is known as character.


A sequence of one or more characters enclosed between single or double quotes is known as String.
Example : (a) ‘Amit’ (b) “5675/X Raigur Pura”

Empty String : A string that does not contain any character is known as Empty String.
Example : (a) S = “” (b) S2 = ‘’
Multiline String : A string that span multiple lines is known as multiline String. It is a sequence of
characters enclosed in triple quotes”
Example : “””
This is a
Multiline string
“”
Indexing of the elements of a string :
With every element (character) of a string , an integer value is associated. This integer value is known as
index or subscript of that element. The index or subscript is used to access the individual element of the
string.
There are two type of indexing :
1. Positive indexing or forward indexing
2. Negative or Backward Indexing

Positive Indexing : In positive indexing , the index of the elements varies from 0 to N-1 where N is the
total number of characters in the string.
Negative Indexing : In negative indexing , the index of the elements varies from -N to -1 where N is the
total number of characters in the string.
Example : Let S = “COMPUTER” then it is stored as follow :

0 1 2 3 4 5 6 7
S C O M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1

ACCESING THE INDIVIDUAL ELEMENT OF STRING :


An individual element of the string can be accessed by using the string name , followed by index
of that element within the square bracket i.e. string_name[ index]
Example : To access the first character of the string S, we have to write S[0] or S[-8]
NOTE :
(a) Positive index of an element is one less than its position. It means index of Kth element from
beginning is K-1.
(b) Negative index of Kth element from beginning is : -(N-K+1)
(c) The built in function len() returns the total number of characters present in the string passed
as an argument to it.
Example : S = “COMPUTER”
N = len(S)
print(“Length of string = “, N )
OUTPUT : Length of string = 8

TRAVERSING THE STRING :


Accessing each element of the string and then processing it ,is known as traversing.
A string can be traversed in two ways :
(i) Iterating through string using indices of elements
(ii) Iterating through string over the elements

(i) Traversal of string over the element :

Syntax : for <variable_name> in <string_name> :


Process(<variable_name>)

Example : S = “COMPUTER”
for ch in S :
print(ch)

0 1 2 3 4 5 6 7
S C O M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1

(ii) Traversal of string using indices of elements

Syntax : for <index_variable> in range( <length of string>) :


Process(<string_name[index_variable]>)
Example :
(i) S = “COMPUTER”
N = len(S)
for i in range(N) :
print(S[i], end = “”)
OUTPUT : COMPUTER
(ii) s = "COMPUTER"
N = len(s)
for i in range(-1,-(N+1), -1) :
print(s*i+, end = “”)
OUTPUT : RETUPMOC

Q. WAP to count the number of vowels in a given string


Ans.
S = input(“Enter a string : “)
V=0
for ch in S :
if ch in ‘aeiouAEIOU’ :
V +=1
print(“Total number of vowels = “ , V)

OR

S = input(“Enter a string : “)
N = len(S)
for i in range(N) :
if S*i+ in ‘aeiouAEIOU’ :
V += 1
print(“Total number of vowels = “, V )

Q WAP to determine whether a given string is a palindrome or not. Example : ‘AMAMA’ is a palindrome.

Case 1 : N = 8
Mid = N/2 = 4
i j
0 1 2 3 4 5 6 7
S C O M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1
J
Case 2 : N = 7
Mid = 7//2 = 3
i mid j
0 1 2 3 4 5 6
S C O M P U T E
-6 -6 -5 -4 -3 -2 -1

Ans:
s = input("Enter a string : ")
N = len(s)
mid = N//2
palin = True # assume that string is a palindrome
j = -1
for i in range(mid) :
if s[i] != s[j] :
palin = False # string is not a palindrome
break
j = j-1

if palin == True :
print("It is a palindrome")
else :
print("It is not a palindrome")

OR

s = input("Enter a string : ")


N = len(s)
mid = N//2
palin = True # assume that string is a palindrome
j = -1 # index of last character
i = 0 # index of first character
while i < mid :
if s[i] != s[j] :
palin = False # string is not a palindrome
break
j = j-1
i=i+1

if palin == True :
print("It is a palindrome")
else :
print("It is not a palindrome")

NOTE : Strings are immutable, meaning that we cannot update them


If we try to update the values in the string then This will result in this error
message:

# TypeError: 'str' object does not support item assignment

Example : S = “COMPUTER”
S*0+ = ‘P’ # ERROR

Q. Write a Program to find the frequency of different characters appeared in a given string.

SPECIAL OPERATORS THAT CAN BE APPLIED ON STRING :


1. Concatenation operator (+) : It joins second string (RHS operand) at the end of first string ( LHS
operand).
Example : S1 = “Hello”
S2 = “World”
S3 = S1+S2
S4 = S2+S1
print(S3)
print(S4)
OUTPUT :
HelloWorld
WorldHello

2. Replicating Operator (*) : It creates a new string by repeating multiple copies the same string.
Syntax : <string_name>*<integer_value/variable>
Example :
S = “Amit”
S1 = S*3
print(S)
print(S1)
OUTPUT :
Amit
AmitAmitAmit
NOTE :
(i) The second operand for replicating operator (*) must be an integer value. It cannot be a
decimal value. If we write a decimal value then it will give an ERROR.
Example : S = “Amit”
S1 = S *3.3 # ERROR
(ii) If the second operand is an integer less than or equal to 0 then it will create an empty string.
Example : S = “Amit”
S1 = S *-2
print(“S1 = “, S1)
OUTPUT :
S1 = ‘ ‘
Q. Find the output :
s = "Amit"

s1 = (s + " ")*3 # concatenation + replication


print("Original string = ", s)
print("After replicate string is : ", s1)
Ans: OUTPUT :
Original String = Amit
After Replicate string is : Amit Amit Amit
3. in : It is known as membership operator. It finds whether a given substring is a member of a
given string. It returns True if the substring is present otherwise returns False.
Syntax : <substring> in < string>
Example: ch = ‘a’
print(ch in “abcdef”)
Ouput : True
4. not in : It is known as membership operator. It finds whether a given substring is a member of a
given string. It returns False if the substring is present otherwise returns True.
Syntax : <substring> not in < string>
Example: ch = ‘a’
print(ch not in “abcdef”)
Ouput : False

Q. WAP to count number of vowels in the given string


Ans.
S = input("Enter the string : ")
vow = 0
for ch in S :
if ch in "AEIOUaeiou" :
vow = vow + 1
print("Number of Vowels = ", vow)

Function : It is a named block of one or more program statements that can be executes as and when
require by calling/invoking the function.
Example :
def calarea():
R = float(input(“Enter Radius :”))
A = 3.14 *R*R
print(“Area of circle = “, A)
#-------------------------------------------------------------------------------------------
calarea() # calling statement

Arguments : The value/values that are passed to function at time of calling it are known as Arguments.
Example :
def calarea(R):
A = 3.14 *R*R
Print(“Area of circle = “, A)
#-------------------------------------------------------------------------------------------
Calarea(3.5) # calling statement
Type of Functions :
1. Built-in Function : Already defined in the python Interpreter ( Ex. float(), input(), print() )
2. User Defined Function : Created BY the Programmer
3. Pre-defined Library Functions ( Defined in python library)

Method : It is a block of one or more statements that acts upon the object.
It differs from the function in the way it is called /used in the program.
The calling statement for the method is as follow :
Object_name.Method_name()
Example : S = “amit”
S1 = S.capitalize()
print(“ S1 = “, s1 )

Q. Find the length of a string using a function


# finding length of a string
def length(S):
N=0
for ch in S :
N = N+1
return(N)

#-----------------------------------
S1 = "Computer"
s2 = "Amit"
L = length(s2)
print("Length of second string = ", L)

STRING METHODS AND BUILT-IN FUNCTIONS :


Python provides several built-in functions and methods which allow to easily modify and manipulate
strings.
1. len() : It is a built in function that returns the total number of characters in the string passed to
it as an argument.

Syntax : len(<string-literal/String_object>)

Example : S = “COMPUTER”
N = len(S) # CALLING SATATEMENT
print(“:Length of string = “ , N)
2. capitalize() : It is a method that returns the exact copy of the string with the first letter in
uppercase form.
Syntax : <String_object>.capitalize()

Example : S= “abc”
S1= S.capitalize() # calling statement
print(“ Original string = “, S)
print(“Capitalize string = “, S1)
OUTPUT:
Original String = abc
Capitalize String = Abc

3. split() : It is a string method that breaks up a string at the specified separator(character) and
returns a list of substrings.

Syntax : <string_object>.split( [separator [, maxsplit] ] )

Where
Separator : It is a delimiter. The string splits at the specified separator. If the separator is not
specified then any whitespace ( space, newline etc ) is a separator.

Maxsplit : It defined the maximum number of splits. The default value of maxsplit is -1 which
means there is no limit on the number of splits.
Example :
Str1 = “ We are learning python”
X = str1.split()
print(X)
OUTPUT :
*‘We’, ‘are’, ‘learning’, ‘python’+
Example :
S = "abcd efgh ijkl mnop xyz"
S.split()
['abcd', 'efgh', 'ijkl', 'mnop', 'xyz']
S = "abcd dfcg gdhcgh hjchs"
S.split('c')
['ab', 'd df', 'g gdh', 'gh hj', 'hs']
S = "c dggdcgh fgchs"
S.split('c')
['', ' dggd', 'gh fg', 'hs']
S.split(sep = ' ', maxsplit = 3)
['abcd', 'efgh', 'ijkl', 'mnop xyz']
S.split(' ', 2)
['abcd', 'efgh', 'ijkl mnop xyz']
S.split(' ', 0)
['abcd efgh ijkl mnop xyz']

Q. Find the output of following code :


str1 = "Blue:Green:Orange:Red"
X = str1.split(':')
print(X)
X = str1.split(':', 1)
print(X)
X = str1.split(':', 5)
print(X)
X = str1.split(':', 0)
print(X)
OUTPUT :
['Blue', 'Green', 'Orange', 'Red']
['Blue', 'Green:Orange:Red']
['Blue', 'Green', 'Orange', 'Red']
['Blue:Green:Orange:Red']

Q. WAP to convert first letter of each word in a string into capital letter and then display the string
Ans.
Str1 = input(“Enter a string : “)
Str2 = “” // empty string
List_words = str1.split()

for word in List_words :


str2 = str2 + “ “ + word.capitalize()

print(“ original string = “, str1)


print(“Converted String = “, str2)

3. Find() : It is a string method that is used to search the first occurrence a given substring in a
given string. It returns the lowest index of the substring if it is found in the string otherwise
return -1.

Syntax : <string_object>.find(<substring>, [start [, end] ] )


Example : Str1 = “blue:green:yellow:red:green”
Str2 = “green”
Str3 = “pink”
Loc = Str1.find(Str2)
print(Loc)
Loc = str1.find(Str3)
Print(Loc)
Loc = str1.find(str2, 5,20)
print(Loc)
OUTPUT :
5
-1
5
Example :
S = "This is a demo of demo of python string"
S.find('demo')
OUTPUT : 10
S.find('Demo')
OUTPUT : -1
S = "This is a demo of demo of python string"
S.find('demo', 15)
Output : 18
S.find('demo', 1,10)
OUTPUT : -1

4. replace() : It is a string method that returns a string by replacing all the occurrences of the old
substring with the new substring.
Syntax : <string_object>.replace(<old sub_string>, <new sub_string>)
Example :
str1 = "Blue:Green:Orange:Red:Green"
str2 = "pink"
str3 = str1.replace("Green", str2)
print("Old String : ", str1)
print(" New string : ", str3)
OUTPUT :
Old String : Blue:Green:Orange:Red:Green
New string : Blue:pink:Orange:Red:pink
STRING SLICING :
Retrieving a substring from a given string is known as string slicing. Chunk of characters can be
extracted from a string using slicing operator (:) in square bracket[].

Syntax : <string_object>[ [start ]: [end] [:step_value] ]

Slice operator return a slice of the string by returning characters falling between the starting position till
end-1. The default value of step is 1.
When step value is K, then it skips k-1 characters while slicing the string from the beginning.
When step value is -K, then it skips k-1 characters while slicing the string from the end.
Example :
0 1 2 3 4 5 6 7
S C O M P U T E R
-8 -7 -6 -5 -4 -3 -2 -1

(i) >>> s = "COMPUTER"


>>> s[:]
'COMPUTER'
>>> s[2:7]
MPUTE
>>> s[:7]
'COMPUTE'
>>> s[2:]
'MPUTER'
>>> s[-2:]
'ER'
>>> s[:-2]
'COMPUT'

(ii) >>> s = "COMPUTER"


>>> s[2:7:2]
'MUE'
>>> s[2:7:3]
'MT'
>>> s[-8:-1]
'COMPUTE'
>>> s[-8:0]
''
>>> s[-8:3]
'COM'
>>> s[-1:-8:-1]
'RETUPMO'
>>> s[:-8:-1]
'RETUPMO'
>>> s[::-1]
'RETUPMOC'

(iii) >>> s = "COMPUTER"


>>> s[::1]
'COMPUTER'
>>> s[::-1]
'RETUPMOC'
>>> s[::-2]
'RTPO'
>>> s[::-3]
'RUO'
>>> s[-1:-8:-3]
'RUO'
>>> s[0:7:-3]
''
Q WAP to check whether a string is a palindrome or not by reversing the string.
Ans.
S = input(“Enter a string : “)
RS = S[: : -1]
if RS == S :
print(“It is palindrome”)
else :
print(“It is not a palindrome”)

You might also like