SlideShare a Scribd company logo
1
CHAPTER 6
Python Strings Revisited
2
Strings
Python treats strings as contiguous series of characters delimited by single, double or even triple quotes.
Python has a built-in string class named "str" that has many useful features.We can simultaneously declare
and define a string by creating a variable of string type.This can be done in several ways which are as follows:
name = "India" graduate = 'N' country = “name nationality” = str("Indian")
Indexing: Individual characters in a string are accessed using the subscript ([ ]) operator.The expression in
brackets is called an index.The index specifies a member of an ordered set and in this case it specifies the
character we want to access from the given set of characters in the string.
The index of the first character is 0 and that of the last character is n-1 where n is the number of characters
in the string. If you try to exceed the bounds (below 0 or above n-1), then an error is raised.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
3
Strings
Traversing a String: A string can be traversed by accessing character(s) from one index to another. For
example, the following program uses indexing to traverse a string from first character to the last.
Example:
4
Concatenating,Appending and Multiplying Strings
Examples:
5
Strings are Immutable
Python strings are immutable which means that once created they cannot be changed.Whenever you try to
modify an existing string variable, a new string is created.
Example:
6
String Formatting Operator
The % operator takes a format string on the left (that has %d, %s, etc) and the corresponding values in a tuple
(will be discussed in subsequent chapter) on the right.The format operator, % allow users to construct strings,
replacing parts of the strings with the data stored in variables.The syntax for the string formatting operation
is:
"<Format>" % (<Values>)
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
7
Built-in String Methods and Functions
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
8
Built-in String Methods and Functions
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
9
Built-in String Methods and Functions
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
10
Slice Operation
A substring of a string is called a slice. The slice operation is used to refer to sub-parts of sequences and
strings.You can take subset of string from original string by using [ ] operator also known as slicing operator.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
11
Specifying Stride while Slicing Strings
In the slice operation, you can specify a third argument as the stride, which refers to the number of characters
to move forward after the first character is retrieved from the string. By default the value of stride is 1, so in
all the above examples where he had not specified the stride, it used the value of 1 which means that every
character between two index numbers is retrieved.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
12
ord() and chr() Functions
ord() function returns the ASCII code of the character and chr() function returns character represented by
a ASCII number.
in and not in Operators
in and not in operators can be used with strings to determine whether a string is present in another string.
Therefore, the in and not in operator are also known as membership operators.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
Examples:
13
Comparing Strings
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
14
Iterating String
String is a sequence type (sequence of characters).You can iterate through the string using for loop.
Examples:
15
The String Module
The string module consist of a number of useful constants, classes and functions (some of which are
deprecated).These functions are used to manipulate strings.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
16
Working with Constants in String Module
You can use the constants defined in the string module along with the find function to classify characters. For
example, if find(lowercase, ch) returns a value except -1, then it means that ch must be a lowercase
character.An alternate way to do the same job is to use the in operator or even the comparison operation.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
17
Program 1 Write a program with a user defined function to count the number of times a character (passed as
argument) occurs in the given string.
Chap4Strings.pdf (from book)
Program 2: Write a program with a user defined function with string as a parameter which replaces all vowels in the
string with '*'.
Program 3: Write a program to input a string from the user and print it in the reverse order without creating a new
string.
Program 4: Write a program which reverses a string passed as parameter and stores the reversed string in a new
string. Use a user defined function for reversing the string
Program 5: Write a program using a user defined function to check if a string is a palindrome or not. (A string is
called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.)
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 18
19
Regular Expressions
Regular Expressions are a powerful tool for various kinds of string manipulation.These are basically a special
text string that is used for describing a search pattern to extract information from text such as code, files,
log, spreadsheets, or even documents.
Regular expressions are a domain specific language (DSL) that is present as a library in most of the modern
programming languages, besides Python.A regular expression is a special sequence of characters that helps to
match or find strings in another string. In Python, regular expressions can be accessed using the re module
which comes as a part of the Standard Library
The Match Function
As the name suggest, the match() function matches a pattern to string with optional flags.The syntax of
match() function is,
re.match (pattern, string, flags=0)
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
20
EXAMPLE- Match() Function
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
21
The search Function
The search() function in the re module searches for a pattern anywhere in the string. Its syntax of can be
given as, re.search(pattern, string, flags=0)
The syntax is similar to the match() function.The function searches for first occurrence of pattern within a
string with optional flags. If the search is successful, a match object is returned and None otherwise.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
22
The sub() Function
The sub() function in the re module can be used to search a pattern in the string and replace it with another
pattern.The syntax of sub() function can be given as, re.sub(pattern, repl, string, max=0)
According to the syntax, the sub() function replaces all occurrences of the pattern in string with repl,
substituting all occurrences unless any max value is provided.This method returns modified string.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
23
The findall() and finditer() Function
The findall() function is used to search a string and returns a list of matches of the pattern in the string. If no
match is found, then the returned list is empty.The syntax of match() function can be given as,
matchList = re.findall(pattern, input_str, flags=0)
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
24
Flag Options
The search(), findall() and match() functions of the module take options to modify the behavior of the
pattern match. Some of these flags are:
re.I or re.IGNORECASE — Ignores case of characters, so "Match", "MATCH", "mAtCh", etc are all same
re.S or re.DOTALL — Enables dot (.) to match newline. By default, dot matches any character other than
the newline character.
re.M or re.MULTILINE — Makes the ^ and $ to match the start and end of each line.That is, it matches even
after and before line breaks in the string. By default, ^ and $ matches the start and end of the whole string.
re.L or re.LOCALE- Makes the flag w to match all characters that are considered letters in the given
current locale settings.
re.U or re.UNICODE- Treats all letters from all scripts as word characters.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
25
Metacharacters in Regular Expression
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
26
Metacharacters in Regular Expression
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
27
Character Classes
When we put the characters to be matched inside square brackets, we call it a character class. For
example, [aeiou] defines a character class that has a vowel character.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Examples:
28
Groups
A group is created by surrounding a part of the regular expression with parentheses.You can even give
group as an argument to the metacharacters such as * and ?.
© OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
Example:
The content of groups in a match can be accessed by using the group() function. For example,
• group(0) or group() returns the whole match.
• group(n), where n is greater than 0, returns the nth group from the left.
• group() returns all groups up from 1.

More Related Content

PPTX
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
PDF
Python regular expressions
DOCX
Python - Regular Expressions
PPT
Adv. python regular expression by Rj
PPTX
trisha comp ppt.pptx
PDF
Lecture 18 - Regular Expressions.pdf
PPTX
PYTHON PPT.pptx python is very useful for day to day life
ODP
PHP Web Programming
FAL(2022-23)_FRESHERS_CSE1012_ETH_AP2022234000166_Reference_Material_I_06-Dec...
Python regular expressions
Python - Regular Expressions
Adv. python regular expression by Rj
trisha comp ppt.pptx
Lecture 18 - Regular Expressions.pdf
PYTHON PPT.pptx python is very useful for day to day life
PHP Web Programming

Similar to chapte_6_String_python_bca_2005_computer (20)

PDF
Module 6 - String Manipulation.pdf
PPTX
Introduction to R for beginners
PPTX
Regular expressions in Python
PPTX
Chapter 3: Introduction to Regular Expression
PPTX
Python Programming Basics for begginners
PPTX
PPTX
Introduction on basic python and it's application
PPTX
C presentation! BATRA COMPUTER CENTRE
PDF
Perl_Part4
PPTX
Unit_I-Introduction python programming (1).pptx
PPTX
The Literals and Variables Concept in Python.pptx
PDF
Python Strings Format
PPT
101 3.7 search text files using regular expressions
PDF
ppt notes python language operators and data
PDF
Maxbox starter20
PPTX
Python ppt_118.pptx
PPTX
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
DOCX
C UNIT-3 PREPARED BY M V B REDDY
PPTX
Chapter - 2.pptx
Module 6 - String Manipulation.pdf
Introduction to R for beginners
Regular expressions in Python
Chapter 3: Introduction to Regular Expression
Python Programming Basics for begginners
Introduction on basic python and it's application
C presentation! BATRA COMPUTER CENTRE
Perl_Part4
Unit_I-Introduction python programming (1).pptx
The Literals and Variables Concept in Python.pptx
Python Strings Format
101 3.7 search text files using regular expressions
ppt notes python language operators and data
Maxbox starter20
Python ppt_118.pptx
PROGRAMMING FOR PROBLEM SOLVING FOR STRING CONCEPT
C UNIT-3 PREPARED BY M V B REDDY
Chapter - 2.pptx
Ad

Recently uploaded (20)

PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PDF
PPT on Performance Review to get promotions
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
UNIT 4 Total Quality Management .pptx
PDF
composite construction of structures.pdf
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
Geodesy 1.pptx...............................................
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPT
Project quality management in manufacturing
PPTX
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Evaluating the Democratization of the Turkish Armed Forces from a Normative P...
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPT on Performance Review to get promotions
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
UNIT 4 Total Quality Management .pptx
composite construction of structures.pdf
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Operating System & Kernel Study Guide-1 - converted.pdf
Geodesy 1.pptx...............................................
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
UNIT-1 - COAL BASED THERMAL POWER PLANTS
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
Foundation to blockchain - A guide to Blockchain Tech
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
Project quality management in manufacturing
Engineering Ethics, Safety and Environment [Autosaved] (1).pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
Ad

chapte_6_String_python_bca_2005_computer

  • 2. 2 Strings Python treats strings as contiguous series of characters delimited by single, double or even triple quotes. Python has a built-in string class named "str" that has many useful features.We can simultaneously declare and define a string by creating a variable of string type.This can be done in several ways which are as follows: name = "India" graduate = 'N' country = “name nationality” = str("Indian") Indexing: Individual characters in a string are accessed using the subscript ([ ]) operator.The expression in brackets is called an index.The index specifies a member of an ordered set and in this case it specifies the character we want to access from the given set of characters in the string. The index of the first character is 0 and that of the last character is n-1 where n is the number of characters in the string. If you try to exceed the bounds (below 0 or above n-1), then an error is raised. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 3. 3 Strings Traversing a String: A string can be traversed by accessing character(s) from one index to another. For example, the following program uses indexing to traverse a string from first character to the last. Example:
  • 5. 5 Strings are Immutable Python strings are immutable which means that once created they cannot be changed.Whenever you try to modify an existing string variable, a new string is created. Example:
  • 6. 6 String Formatting Operator The % operator takes a format string on the left (that has %d, %s, etc) and the corresponding values in a tuple (will be discussed in subsequent chapter) on the right.The format operator, % allow users to construct strings, replacing parts of the strings with the data stored in variables.The syntax for the string formatting operation is: "<Format>" % (<Values>) © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 7. 7 Built-in String Methods and Functions © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 8. 8 Built-in String Methods and Functions © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 9. 9 Built-in String Methods and Functions © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 10. 10 Slice Operation A substring of a string is called a slice. The slice operation is used to refer to sub-parts of sequences and strings.You can take subset of string from original string by using [ ] operator also known as slicing operator. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 11. 11 Specifying Stride while Slicing Strings In the slice operation, you can specify a third argument as the stride, which refers to the number of characters to move forward after the first character is retrieved from the string. By default the value of stride is 1, so in all the above examples where he had not specified the stride, it used the value of 1 which means that every character between two index numbers is retrieved. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 12. 12 ord() and chr() Functions ord() function returns the ASCII code of the character and chr() function returns character represented by a ASCII number. in and not in Operators in and not in operators can be used with strings to determine whether a string is present in another string. Therefore, the in and not in operator are also known as membership operators. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples: Examples:
  • 13. 13 Comparing Strings © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 14. 14 Iterating String String is a sequence type (sequence of characters).You can iterate through the string using for loop. Examples:
  • 15. 15 The String Module The string module consist of a number of useful constants, classes and functions (some of which are deprecated).These functions are used to manipulate strings. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 16. 16 Working with Constants in String Module You can use the constants defined in the string module along with the find function to classify characters. For example, if find(lowercase, ch) returns a value except -1, then it means that ch must be a lowercase character.An alternate way to do the same job is to use the in operator or even the comparison operation. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 17. 17 Program 1 Write a program with a user defined function to count the number of times a character (passed as argument) occurs in the given string. Chap4Strings.pdf (from book) Program 2: Write a program with a user defined function with string as a parameter which replaces all vowels in the string with '*'. Program 3: Write a program to input a string from the user and print it in the reverse order without creating a new string. Program 4: Write a program which reverses a string passed as parameter and stores the reversed string in a new string. Use a user defined function for reversing the string Program 5: Write a program using a user defined function to check if a string is a palindrome or not. (A string is called palindrome if it reads same backwards as forward. For example, Kanak is a palindrome.)
  • 18. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. 18
  • 19. 19 Regular Expressions Regular Expressions are a powerful tool for various kinds of string manipulation.These are basically a special text string that is used for describing a search pattern to extract information from text such as code, files, log, spreadsheets, or even documents. Regular expressions are a domain specific language (DSL) that is present as a library in most of the modern programming languages, besides Python.A regular expression is a special sequence of characters that helps to match or find strings in another string. In Python, regular expressions can be accessed using the re module which comes as a part of the Standard Library The Match Function As the name suggest, the match() function matches a pattern to string with optional flags.The syntax of match() function is, re.match (pattern, string, flags=0) © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 20. 20 EXAMPLE- Match() Function © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 21. 21 The search Function The search() function in the re module searches for a pattern anywhere in the string. Its syntax of can be given as, re.search(pattern, string, flags=0) The syntax is similar to the match() function.The function searches for first occurrence of pattern within a string with optional flags. If the search is successful, a match object is returned and None otherwise. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 22. 22 The sub() Function The sub() function in the re module can be used to search a pattern in the string and replace it with another pattern.The syntax of sub() function can be given as, re.sub(pattern, repl, string, max=0) According to the syntax, the sub() function replaces all occurrences of the pattern in string with repl, substituting all occurrences unless any max value is provided.This method returns modified string. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example:
  • 23. 23 The findall() and finditer() Function The findall() function is used to search a string and returns a list of matches of the pattern in the string. If no match is found, then the returned list is empty.The syntax of match() function can be given as, matchList = re.findall(pattern, input_str, flags=0) © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 24. 24 Flag Options The search(), findall() and match() functions of the module take options to modify the behavior of the pattern match. Some of these flags are: re.I or re.IGNORECASE — Ignores case of characters, so "Match", "MATCH", "mAtCh", etc are all same re.S or re.DOTALL — Enables dot (.) to match newline. By default, dot matches any character other than the newline character. re.M or re.MULTILINE — Makes the ^ and $ to match the start and end of each line.That is, it matches even after and before line breaks in the string. By default, ^ and $ matches the start and end of the whole string. re.L or re.LOCALE- Makes the flag w to match all characters that are considered letters in the given current locale settings. re.U or re.UNICODE- Treats all letters from all scripts as word characters. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 25. 25 Metacharacters in Regular Expression © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 26. 26 Metacharacters in Regular Expression © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED.
  • 27. 27 Character Classes When we put the characters to be matched inside square brackets, we call it a character class. For example, [aeiou] defines a character class that has a vowel character. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Examples:
  • 28. 28 Groups A group is created by surrounding a part of the regular expression with parentheses.You can even give group as an argument to the metacharacters such as * and ?. © OXFORD UNIVERSITY PRESS 2017.ALL RIGHTS RESERVED. Example: The content of groups in a match can be accessed by using the group() function. For example, • group(0) or group() returns the whole match. • group(n), where n is greater than 0, returns the nth group from the left. • group() returns all groups up from 1.