SlideShare a Scribd company logo
1 of 41
Strings
A string is a sequence
• A string is a sequence of characters. You can access
the characters one at a time with the bracket operator.
• Ex:
>>> fruit = 'banana'
>>> letter = fruit[1]
>>> print letter
a
Contd..
• You can use any expression, including variables and
operators, as an index, but the value of the index has
to be an integer. Otherwise you get:
• Ex:
>>> letter = fruit[1.5]
TypeError: string indices must be integers, not float
When the above code is executed, it produces the following result
Contd..
Updating Strings
• You can "update" an existing string by (re)assigning a variable to
another string.
• The new value can be related to its previous value or to a
completely different string altogether.
Contd….
When the above code is executed, it produces the following result
How to change or delete a string?
Contd..
len
• len is a built-in function that returns the number of
characters in a string.
• Ex:
>>> fruit = 'banana'
>>> len(fruit)
6
• To get the last character we can use as following.
Contd..
• Ex:
>>>Length=len(fruit);
>>>last = fruit[length-1]
a
Traversal with a for loop
• Traversal: Start at the beginning, select each character in
turn, do something to it, and continue until the end.
• Ex:
index = 0
while index < len(fruit):
letter = fruit[index]
print (letter)
index = index + 1
Contd..
• Another way to write a traversal is with a for loop:
• Ex:
for char in fruit:
print (char)
• Ex2: Write a function that takes a string as an
argument and displays the letters backward, one per
line.
Contd..
• Ex:
prefixes = 'JKLMNOPQ'
suffix = 'ack'
for letter in prefixes:
print (letter + suffix)
String slices
• A segment of a string is called a slice.
• Ex:
>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python
Contd..
• The operator [n:m] returns the part of the string
from the “n-eth” character to the “m-eth” character,
including the first but excluding the last.
• If you omit the first index (before the colon), the
slice starts at the beginning of the string.
• If you omit the second index, the slice goes to the
end of the string:
Contd..
• Ex:
>>> fruit = 'banana'
>>> fruit[:3]
'ban'
>>> fruit[3:]
'ana‘
• If the first index is greater than or equal to the second the
result is an empty string, represented by two quotation
marks.
Contd..
• Ex:
>>> fruit = 'banana'
>>> fruit[3:3]
‘ ‘
• An empty string contains no characters and has
length 0
Strings are immutable
• It is tempting to use the [] operator on the left side of an
assignment, with the intention of changing a character in
a string. For example:
>>> greeting = 'Hello, world!'
>>> greeting[0] = 'J'
TypeError: 'str' object does not support item assignment
• The reason for the error is that strings are immutable,
which means you can’t change an existing string.
Contd..
>>> greeting = 'Hello, world!'
>>> new_greeting = 'J' + greeting[1:]
>>> print new_greeting
Jello, world!
Searching
• Traversing a sequence and returning when we find
what we are looking for—is called a search.
• Ex:
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
Contd..
• Ex: Modify find so that it has a third parameter, the
index in word where it should start looking.
def find(word, letter, index):
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
Looping and counting
• The following program counts the number of times the
letter a appears in a string:
• Ex:
word = 'banana'
count = 0
for letter in word:
if letter == 'a':
count = count + 1
print count
Contd..
• Ex2:Encapsulate this code in a function named
count, and generalize it so that it accepts the string
and the letter as arguments.
Contd..
def count(word,letter):
counter=0
for var in word:
if var==letter :
counter = counter + 1
if counter>0:
return counter
else:
return -1
• Ex3:Rewrite this function so that instead of
traversing the string, it uses the three parameter
version of find from the previous section.
String Methods
• S.lower() and S.lower(): Returns the lowercase and upper case
version of the string. The .upper() and .lower() string methods
are self-explanatory.
• Performing the .upper() method on a string converts all of the
characters to uppercase, whereas the lower() method converts all
of the characters to lowercase.
Replace
• S.replace('old', 'new'): Returns a string where all
occurrences of 'old' have been replaced by 'new'
Split
• At some point, you may need to break a large string down into smaller
chunks, or strings. This is the opposite of concatenation which merges
or combines strings into one. To do this, you use the split function.
• S.split('delim') : Split() splits or breakup a string and add the data to a
string array using a defined separator.
• If no separator is defined when you call upon the function, whitespace
will be by default. In simpler terms, the separator is a defined character
that will be placed between each variable.
Example
When the above code is executed, it produces the following result
JOIN
• s.join(list): The method join () returns a string in which the
string elements of sequence have been joined by str
separator. Opposite of split(),joins the elements in the
given list together using the string as the delimiter.
• Syntax
•
Example
When the above code is executed, it produces the following result
String capitalize() Method
• It returns a copy of the string with only its first character
capitalized.
Find and len()
Reversing String
• By using the reversed function, you can reverse the string.
• Ex:
str=“banana”
str1=“ ”.join(reversed(str))
print(str1)
Or
str="Pine Apple"
str1=str[::-1]
print(str1)
Contd..
Contd…
String function Operation
str.isalpha() Return true if str contain all letters
str.isdigit() Return true if str contain all digits
str.islower() Return true if str contain all small
letters
str.isupper() Return true if str contain all
uppercase letters
str.replace(w,t) Replace all occurrences of w with t.
str.strip(w) Remove the starting or ending
letters of str
Contd..
Function Operation
s.count(char) Return count of char in s
s.index(char) Return index of char in s
min(s) Return min character in s
max(s) Return max character in s
s==w comparison
The in operator
The word in is a boolean operator that takes two strings
and returns True if the first appears as a substring in
the second.
Ex:
>>> 'a' in 'banana'
True
>>> 'seed' in 'banana'
False
Contd..
• Ex:
if char not in 'ABCDEFG':
print('Invalid musical note character found')
if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
print(‘Capital letter')
if char in 'abcdefghijklmnopqrstuvwxyz'
print(‘Small letter')
if char in '0123456789‘
print(‘Digit')
String comparison
• The relational operators work on strings.
• Ex:
if word < 'banana':
print 'Your word,' + word + ', comes before banana.'
elif word > 'banana':
print 'Your word,' + word + ', comes after banana.'
else:
print 'All right, bananas.'

More Related Content

Similar to Strings.pptx

15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4Syed Mustafa
 
Python Strings Methods
Python Strings MethodsPython Strings Methods
Python Strings MethodsMr Examples
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptxYagna15
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxpriestmanmable
 
The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88Mahmoud Samir Fayed
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptxssuserc755f1
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Ziyauddin Shaik
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 

Similar to Strings.pptx (20)

15CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 415CS664-Python Application Programming - Module 3 and 4
15CS664-Python Application Programming - Module 3 and 4
 
Python Strings Methods
Python Strings MethodsPython Strings Methods
Python Strings Methods
 
Lists.pptx
Lists.pptxLists.pptx
Lists.pptx
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
 
The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88The Ring programming language version 1.3 book - Part 11 of 88
The Ring programming language version 1.3 book - Part 11 of 88
 
Python data handling
Python data handlingPython data handling
Python data handling
 
Python_Unit_III.pptx
Python_Unit_III.pptxPython_Unit_III.pptx
Python_Unit_III.pptx
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
Python basics
Python basicsPython basics
Python basics
 
String.pdf
String.pdfString.pdf
String.pdf
 
Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )Introduction to python programming ( part-3 )
Introduction to python programming ( part-3 )
 
Day2
Day2Day2
Day2
 
Python ppt
Python pptPython ppt
Python ppt
 
Python basics
Python basicsPython basics
Python basics
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 

Recently uploaded

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...Soham Mondal
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
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
 
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 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
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
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
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingrakeshbaidya232001
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxAsutosh Ranjan
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
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
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
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
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Recently uploaded (20)

OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
OSVC_Meta-Data based Simulation Automation to overcome Verification Challenge...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
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...
 
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 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
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
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
 
Porous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writingPorous Ceramics seminar and technical writing
Porous Ceramics seminar and technical writing
 
Coefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptxCoefficient of Thermal Expansion and their Importance.pptx
Coefficient of Thermal Expansion and their Importance.pptx
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
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
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
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...
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Strings.pptx

  • 2. A string is a sequence • A string is a sequence of characters. You can access the characters one at a time with the bracket operator. • Ex: >>> fruit = 'banana' >>> letter = fruit[1] >>> print letter a
  • 3. Contd.. • You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. Otherwise you get: • Ex: >>> letter = fruit[1.5] TypeError: string indices must be integers, not float
  • 4. When the above code is executed, it produces the following result Contd..
  • 5. Updating Strings • You can "update" an existing string by (re)assigning a variable to another string. • The new value can be related to its previous value or to a completely different string altogether.
  • 6. Contd…. When the above code is executed, it produces the following result
  • 7. How to change or delete a string?
  • 9. len • len is a built-in function that returns the number of characters in a string. • Ex: >>> fruit = 'banana' >>> len(fruit) 6 • To get the last character we can use as following.
  • 11. Traversal with a for loop • Traversal: Start at the beginning, select each character in turn, do something to it, and continue until the end. • Ex: index = 0 while index < len(fruit): letter = fruit[index] print (letter) index = index + 1
  • 12. Contd.. • Another way to write a traversal is with a for loop: • Ex: for char in fruit: print (char) • Ex2: Write a function that takes a string as an argument and displays the letters backward, one per line.
  • 13. Contd.. • Ex: prefixes = 'JKLMNOPQ' suffix = 'ack' for letter in prefixes: print (letter + suffix)
  • 14. String slices • A segment of a string is called a slice. • Ex: >>> s = 'Monty Python' >>> print s[0:5] Monty >>> print s[6:12] Python
  • 15. Contd.. • The operator [n:m] returns the part of the string from the “n-eth” character to the “m-eth” character, including the first but excluding the last. • If you omit the first index (before the colon), the slice starts at the beginning of the string. • If you omit the second index, the slice goes to the end of the string:
  • 16. Contd.. • Ex: >>> fruit = 'banana' >>> fruit[:3] 'ban' >>> fruit[3:] 'ana‘ • If the first index is greater than or equal to the second the result is an empty string, represented by two quotation marks.
  • 17. Contd.. • Ex: >>> fruit = 'banana' >>> fruit[3:3] ‘ ‘ • An empty string contains no characters and has length 0
  • 18. Strings are immutable • It is tempting to use the [] operator on the left side of an assignment, with the intention of changing a character in a string. For example: >>> greeting = 'Hello, world!' >>> greeting[0] = 'J' TypeError: 'str' object does not support item assignment • The reason for the error is that strings are immutable, which means you can’t change an existing string.
  • 19. Contd.. >>> greeting = 'Hello, world!' >>> new_greeting = 'J' + greeting[1:] >>> print new_greeting Jello, world!
  • 20. Searching • Traversing a sequence and returning when we find what we are looking for—is called a search. • Ex: def find(word, letter): index = 0 while index < len(word): if word[index] == letter: return index index = index + 1 return -1
  • 21. Contd.. • Ex: Modify find so that it has a third parameter, the index in word where it should start looking. def find(word, letter, index): while index < len(word): if word[index] == letter: return index index = index + 1 return -1
  • 22. Looping and counting • The following program counts the number of times the letter a appears in a string: • Ex: word = 'banana' count = 0 for letter in word: if letter == 'a': count = count + 1 print count
  • 23. Contd.. • Ex2:Encapsulate this code in a function named count, and generalize it so that it accepts the string and the letter as arguments.
  • 24. Contd.. def count(word,letter): counter=0 for var in word: if var==letter : counter = counter + 1 if counter>0: return counter else: return -1
  • 25. • Ex3:Rewrite this function so that instead of traversing the string, it uses the three parameter version of find from the previous section.
  • 26. String Methods • S.lower() and S.lower(): Returns the lowercase and upper case version of the string. The .upper() and .lower() string methods are self-explanatory. • Performing the .upper() method on a string converts all of the characters to uppercase, whereas the lower() method converts all of the characters to lowercase.
  • 27.
  • 28. Replace • S.replace('old', 'new'): Returns a string where all occurrences of 'old' have been replaced by 'new'
  • 29. Split • At some point, you may need to break a large string down into smaller chunks, or strings. This is the opposite of concatenation which merges or combines strings into one. To do this, you use the split function. • S.split('delim') : Split() splits or breakup a string and add the data to a string array using a defined separator. • If no separator is defined when you call upon the function, whitespace will be by default. In simpler terms, the separator is a defined character that will be placed between each variable.
  • 30. Example When the above code is executed, it produces the following result
  • 31. JOIN • s.join(list): The method join () returns a string in which the string elements of sequence have been joined by str separator. Opposite of split(),joins the elements in the given list together using the string as the delimiter. • Syntax •
  • 32. Example When the above code is executed, it produces the following result
  • 33. String capitalize() Method • It returns a copy of the string with only its first character capitalized.
  • 35. Reversing String • By using the reversed function, you can reverse the string. • Ex: str=“banana” str1=“ ”.join(reversed(str)) print(str1) Or str="Pine Apple" str1=str[::-1] print(str1)
  • 37. Contd… String function Operation str.isalpha() Return true if str contain all letters str.isdigit() Return true if str contain all digits str.islower() Return true if str contain all small letters str.isupper() Return true if str contain all uppercase letters str.replace(w,t) Replace all occurrences of w with t. str.strip(w) Remove the starting or ending letters of str
  • 38. Contd.. Function Operation s.count(char) Return count of char in s s.index(char) Return index of char in s min(s) Return min character in s max(s) Return max character in s s==w comparison
  • 39. The in operator The word in is a boolean operator that takes two strings and returns True if the first appears as a substring in the second. Ex: >>> 'a' in 'banana' True >>> 'seed' in 'banana' False
  • 40. Contd.. • Ex: if char not in 'ABCDEFG': print('Invalid musical note character found') if char in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' print(‘Capital letter') if char in 'abcdefghijklmnopqrstuvwxyz' print(‘Small letter') if char in '0123456789‘ print(‘Digit')
  • 41. String comparison • The relational operators work on strings. • Ex: if word < 'banana': print 'Your word,' + word + ', comes before banana.' elif word > 'banana': print 'Your word,' + word + ', comes after banana.' else: print 'All right, bananas.'