SlideShare a Scribd company logo
1 of 14
Download to read offline
Computer Science
Class XI ( As per CBSE Board)
Chapter 11
Strings
New
syllabus
2023-24
Visit : python.mykvs.in for regular updates
String
String is a sequence of characters,which is enclosed
between either single (' ') or double quotes (" "),
python treats both single and double quotes same.
Visit : python.mykvs.in for regular updates
Creating String
Creation of string in python is very easy.
e.g.
a=‘Computer Science'
b=“Informatics Practices“
Accessing String Elements
e.g.
str='Computer Sciene'
print('str-', str)
print('str[0]-', str[0])
print('str[1:4]-', str[1:4])
print('str[2:]-', str[2:])
print('str *2-', str *2 ) OUTPUT
print("str +'yes'-", str +'yes')
('str-', 'Computer Sciene')
('str[0]-', 'C')
('str[1:4]-', 'omp')
('str[2:]-', 'mputer Sciene')
('str *2-', 'Computer
ScieneComputer Sciene')
("str +'yes'-", 'Computer
Scieneyes')
String
Visit : python.mykvs.in for regular updates
Iterating/Traversing through string
Each character of the string can be accessed sequentially using for
loop.
e.g.
str='Computer Sciene‘ OUTPUT
for i in str:
print(i)
C
o
m
p
u
t
e
r
S
c
i
e
n
e
String
Visit : python.mykvs.in for regular updates
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 .
e.g.program
print("Maria" == "Manoj")
print("Maria" != "Manoj")
print("Maria" > "Manoj")
print("Maria" >= "Manoj")
print("Maria" < "Manoj")
print("Maria" <= "Manoj")
print("Maria" > "")
OUTPUT
False
True
True
True
False
False
True
String
Visit : python.mykvs.in for regular updates
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
Visit : python.mykvs.in for regular updates
String Special Operators
e.g.
a=“comp”
B=“sc”
Operator Description Example
+ Concatenation – to add two strings a + b = comp sc
* Replicate same string multiple times (Repetition) a*2 = compcomp
[] Character of the string a[1] will give o
[ : ] Range Slice –Range string a[1:4] will give omp
in Membership check p in a will give 1
not in Membership check for non availability M not in a will give 1
% Format the string
print ("My Subject is %s and class is %d" % ('Comp Sc', 11))
String
Visit : python.mykvs.in for regular updates
Format Symbol
%s -string conversion via str() prior to formatting
%i -signed decimal integer
%d -signed decimal integer
%u -unsigned decimal integer
%o -octal integer
%x -hexadecimal integer (lowercase letters)
%X -hexadecimal integer (UPPERcase letters)
%e -exponential notation (with lowercase 'e')
%E -exponential notation (with UPPERcase 'E')
%f -floating point real number
%c -character
%G -the shorter of %f and %E
String
Visit : python.mykvs.in for regular updates
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
Visit : python.mykvs.in for regular updates
String functions and methods
a=“comp”
b=“my comp”
Method Result Example
len() Returns the length of the string r=len(a) will be 4
str.capitalize() To capitalize the string r=a.capitalize() will be “COMP”
str.title() Will return title case string
str.upper() Will return string in upper case r=a.upper() will be “COMP”
str.lower() Will return string in lower case r=a.upper() will be “comp”
str.count()
will return the total count of a
given element in a string
r=a.count(‘o’) will be 1
str.find(sub)
To find the substring position(starts
from 0 index)
r=a.find (‘m’) will be 2
str.replace()
Return the string with replaced sub
strings
r=b.replace(‘my’,’your’) will be ‘your
comp’
String
Visit : python.mykvs.in for regular updates
String functions and methods
a=“comp”
Method Result Example
str.index() Returns index position of substring
r=a.index(‘om’) will
be 1
str.isalnum()
String consists of only alphanumeric characters (no
symbols)
r=a.isalnum() will
return True
str.isalpha() String consists of only alphabetic characters (no symbols)
str.islower() String’s alphabetic characters are all lower case
str.isnumeric() String consists of only numeric characters
str.isspace() String consists of only whitespace characters
str.istitle() String is in title case
str.isupper() String’s alphabetic characters are all upper case
String
Visit : python.mykvs.in for regular updates
String functions and methods
a=“comp”
Method Result Example
str.lstrip(char)
str.rstrip(char)
Returns a copy of the string with leading/trailing
characters removed
b=‘**comp’;
r=b.lstrin() will be
‘comp’
str.strip(char)
Removes specific character from leading and trailing
position
str.split() Returns list of strings as splitted
b=‘my comp’;
r=b.split() will be
[‘my’,‘comp’]
str.partition() Partition the string on first occurrence of substring
b=‘my comp’;
r=b.partition(‘comp’
) will be
[‘my’,‘comp’]
String
Visit : python.mykvs.in for regular updates
#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(i.isdigit()):
count1=count1+1
count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)
String
Visit : python.mykvs.in for regular updates
Searching for Substrings
METHOD NAME METHODS DESCRIPTION:
endswith(s1: str): bool Returns True if strings ends
with substring s1
startswith(s1: str): bool Returns True if strings starts
with substring s1
count(substring): int Returns number of
occurrences of substring the
string
find(s1): int Returns lowest index from
where s1 starts in the string,
if string not found returns -1
rfind(s1): int Returns highest index from
where s1 starts in the string,
if string not found returns -1
E.g. program
s = "welcome to python"
print(s.endswith("thon"))
print(s.startswith("good"))
print(s.find("come"))
print(s.find("become"))
print(s.rfind("o"))
print(s.count("o"))
OUTPUT
True
False
3
-1
15
3
String
Visit : python.mykvs.in for regular updates

More Related Content

Similar to strings11.pdf

5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing웅식 전
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSowmyaJyothi3
 
Numpy string functions
Numpy string functionsNumpy string functions
Numpy string functionsTONO KURIAKOSE
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsMegha V
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88Mahmoud Samir Fayed
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212Mahmoud Samir Fayed
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02Abdul Samee
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiSowmya Jyothi
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)teach4uin
 
Python Strings Methods
Python Strings MethodsPython Strings Methods
Python Strings MethodsMr Examples
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayUtkarsh Sengar
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Chia-Chi Chang
 

Similar to strings11.pdf (20)

5 2. string processing
5 2. string processing5 2. string processing
5 2. string processing
 
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdfSTRINGS IN C MRS.SOWMYA JYOTHI.pdf
STRINGS IN C MRS.SOWMYA JYOTHI.pdf
 
Numpy string functions
Numpy string functionsNumpy string functions
Numpy string functions
 
Strings part2
Strings part2Strings part2
Strings part2
 
Python programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operationsPython programming: Anonymous functions, String operations
Python programming: Anonymous functions, String operations
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Computer programming 2 Lesson 12
Computer programming 2  Lesson 12Computer programming 2  Lesson 12
Computer programming 2 Lesson 12
 
Strings in c
Strings in cStrings in c
Strings in c
 
Strings
StringsStrings
Strings
 
Ch2
Ch2Ch2
Ch2
 
The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88The Ring programming language version 1.3 book - Part 26 of 88
The Ring programming language version 1.3 book - Part 26 of 88
 
Unitii string
Unitii stringUnitii string
Unitii string
 
The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212The Ring programming language version 1.10 book - Part 45 of 212
The Ring programming language version 1.10 book - Part 45 of 212
 
16 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp0216 strings-and-text-processing-120712074956-phpapp02
16 strings-and-text-processing-120712074956-phpapp02
 
Strings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothiStrings in c mrs.sowmya jyothi
Strings in c mrs.sowmya jyothi
 
L13 string handling(string class)
L13 string handling(string class)L13 string handling(string class)
L13 string handling(string class)
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
 
Python Strings Methods
Python Strings MethodsPython Strings Methods
Python Strings Methods
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)Learning notes of r for python programmer (Temp1)
Learning notes of r for python programmer (Temp1)
 

Recently uploaded

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSISrknatarajan
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxupamatechverse
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSKurinjimalarL3
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxpurnimasatapathy1234
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...RajaP95
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxpranjaldaimarysona
 

Recently uploaded (20)

UNIT-III FMM. DIMENSIONAL ANALYSIS
UNIT-III FMM.        DIMENSIONAL ANALYSISUNIT-III FMM.        DIMENSIONAL ANALYSIS
UNIT-III FMM. DIMENSIONAL ANALYSIS
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Introduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptxIntroduction and different types of Ethernet.pptx
Introduction and different types of Ethernet.pptx
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICSAPPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
APPLICATIONS-AC/DC DRIVES-OPERATING CHARACTERISTICS
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Microscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptxMicroscopic Analysis of Ceramic Materials.pptx
Microscopic Analysis of Ceramic Materials.pptx
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
IMPLICATIONS OF THE ABOVE HOLISTIC UNDERSTANDING OF HARMONY ON PROFESSIONAL E...
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
Processing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptxProcessing & Properties of Floor and Wall Tiles.pptx
Processing & Properties of Floor and Wall Tiles.pptx
 

strings11.pdf

  • 1. Computer Science Class XI ( As per CBSE Board) Chapter 11 Strings New syllabus 2023-24 Visit : python.mykvs.in for regular updates
  • 2. String String is a sequence of characters,which is enclosed between either single (' ') or double quotes (" "), python treats both single and double quotes same. Visit : python.mykvs.in for regular updates
  • 3. Creating String Creation of string in python is very easy. e.g. a=‘Computer Science' b=“Informatics Practices“ Accessing String Elements e.g. str='Computer Sciene' print('str-', str) print('str[0]-', str[0]) print('str[1:4]-', str[1:4]) print('str[2:]-', str[2:]) print('str *2-', str *2 ) OUTPUT print("str +'yes'-", str +'yes') ('str-', 'Computer Sciene') ('str[0]-', 'C') ('str[1:4]-', 'omp') ('str[2:]-', 'mputer Sciene') ('str *2-', 'Computer ScieneComputer Sciene') ("str +'yes'-", 'Computer Scieneyes') String Visit : python.mykvs.in for regular updates
  • 4. Iterating/Traversing through string Each character of the string can be accessed sequentially using for loop. e.g. str='Computer Sciene‘ OUTPUT for i in str: print(i) C o m p u t e r S c i e n e String Visit : python.mykvs.in for regular updates
  • 5. 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 . e.g.program print("Maria" == "Manoj") print("Maria" != "Manoj") print("Maria" > "Manoj") print("Maria" >= "Manoj") print("Maria" < "Manoj") print("Maria" <= "Manoj") print("Maria" > "") OUTPUT False True True True False False True String Visit : python.mykvs.in for regular updates
  • 6. 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 Visit : python.mykvs.in for regular updates
  • 7. String Special Operators e.g. a=“comp” B=“sc” Operator Description Example + Concatenation – to add two strings a + b = comp sc * Replicate same string multiple times (Repetition) a*2 = compcomp [] Character of the string a[1] will give o [ : ] Range Slice –Range string a[1:4] will give omp in Membership check p in a will give 1 not in Membership check for non availability M not in a will give 1 % Format the string print ("My Subject is %s and class is %d" % ('Comp Sc', 11)) String Visit : python.mykvs.in for regular updates
  • 8. Format Symbol %s -string conversion via str() prior to formatting %i -signed decimal integer %d -signed decimal integer %u -unsigned decimal integer %o -octal integer %x -hexadecimal integer (lowercase letters) %X -hexadecimal integer (UPPERcase letters) %e -exponential notation (with lowercase 'e') %E -exponential notation (with UPPERcase 'E') %f -floating point real number %c -character %G -the shorter of %f and %E String Visit : python.mykvs.in for regular updates
  • 9. 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 Visit : python.mykvs.in for regular updates
  • 10. String functions and methods a=“comp” b=“my comp” Method Result Example len() Returns the length of the string r=len(a) will be 4 str.capitalize() To capitalize the string r=a.capitalize() will be “COMP” str.title() Will return title case string str.upper() Will return string in upper case r=a.upper() will be “COMP” str.lower() Will return string in lower case r=a.upper() will be “comp” str.count() will return the total count of a given element in a string r=a.count(‘o’) will be 1 str.find(sub) To find the substring position(starts from 0 index) r=a.find (‘m’) will be 2 str.replace() Return the string with replaced sub strings r=b.replace(‘my’,’your’) will be ‘your comp’ String Visit : python.mykvs.in for regular updates
  • 11. String functions and methods a=“comp” Method Result Example str.index() Returns index position of substring r=a.index(‘om’) will be 1 str.isalnum() String consists of only alphanumeric characters (no symbols) r=a.isalnum() will return True str.isalpha() String consists of only alphabetic characters (no symbols) str.islower() String’s alphabetic characters are all lower case str.isnumeric() String consists of only numeric characters str.isspace() String consists of only whitespace characters str.istitle() String is in title case str.isupper() String’s alphabetic characters are all upper case String Visit : python.mykvs.in for regular updates
  • 12. String functions and methods a=“comp” Method Result Example str.lstrip(char) str.rstrip(char) Returns a copy of the string with leading/trailing characters removed b=‘**comp’; r=b.lstrin() will be ‘comp’ str.strip(char) Removes specific character from leading and trailing position str.split() Returns list of strings as splitted b=‘my comp’; r=b.split() will be [‘my’,‘comp’] str.partition() Partition the string on first occurrence of substring b=‘my comp’; r=b.partition(‘comp’ ) will be [‘my’,‘comp’] String Visit : python.mykvs.in for regular updates
  • 13. #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(i.isdigit()): count1=count1+1 count2=count2+1 print("The number of digits is:") print(count1) print("The number of characters is:") print(count2) String Visit : python.mykvs.in for regular updates
  • 14. Searching for Substrings METHOD NAME METHODS DESCRIPTION: endswith(s1: str): bool Returns True if strings ends with substring s1 startswith(s1: str): bool Returns True if strings starts with substring s1 count(substring): int Returns number of occurrences of substring the string find(s1): int Returns lowest index from where s1 starts in the string, if string not found returns -1 rfind(s1): int Returns highest index from where s1 starts in the string, if string not found returns -1 E.g. program s = "welcome to python" print(s.endswith("thon")) print(s.startswith("good")) print(s.find("come")) print(s.find("become")) print(s.rfind("o")) print(s.count("o")) OUTPUT True False 3 -1 15 3 String Visit : python.mykvs.in for regular updates