String
String is a sequence of characters, which is enclosed between either single (' ') or double quotes ("
"), python treats both single and double quotes same.
Creating String Creation of string in python is very easy.
e.g. a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements
Iterating/Traversing through string Each character of the string can be accessed sequentially using
for loop.
e.g.
str='Computer Sciene‘
for i in str:
print(i)
output-
C
O
M
P
U
R
String comparison
We can use ( > , < , <= , <= , == , != ) to compare two strings.
Python compares string lexicographically i.e using ASCII value of the characters.
Suppose you have str1 as "Maria" and str2 as "Manoj" . The first two characters from str1 and str2 (
M and M ) are compared. As they are equal, the second two characters are compared. Because they
are also equal, the third two characters ( r and n ) are compared. And because 'r' has greater ASCII
value than ‘n' , str1 is greater than str2 .
Updating Strings
String value can be updated by reassigning another value in it.
e.g.
var1 = 'Comp Sc'
var1 = var1[:7] + ' with Python'
print ("Updated String :- ",var1 )
OUTPUT
('Updated String :- ', 'Comp Sc with Python')
String Special Operators
e.g.
a=“comp”
b=“sc”
Triple Quotes It is used to create string with multiple lines.
e.g.
Str1 = “””This course will introduce the learner to text mining and text manipulation basics. The
course begins with an understanding of how text is handled by python”””
String functions and methods
a=“comp”
b=“my comp”
a=“comp”
String functions and methods
a=“comp”
#Python Program to calculate the number of digits and letters in a string
string=raw_input("Enter string:")
count1=0
count2=0
for i in string:
if([Link]()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)