SlideShare a Scribd company logo
1 of 93
Download to read offline
BCSE101E Computer Programming: Python
School of Mechanical Engineering (SMEC)
1
B.Tech. Mechanical Engineering
Fall 23-24
2
Module-5: Strings and Regular Expressions
Strings: Comparison, Formatting, Slicing, Splitting, Stripping – Regular
Expressions: Matching, Search and replace, Patterns (2 Hours)
3
String Comparison
String Comparison
4
• The ways to compare two strings in Python are
• By using == (equal to) operator
• By using != (not equal to) operator
• By using sorted() method
• By using is operator
• By using Comparison operators
String Comparison
5
By using == (equal to) operator
String Comparison
6
By using != (not equal to) operator
String Comparison
7
By using sorted method
String Comparison
8
By using is operator
String Comparison
9
By using comparison/ relational operators
• Python string comparison is performed using the characters in both
strings
• The characters in both strings are compared one by one
• When different characters are found then their Unicode value is
compared
• The character with lower Unicode value is considered to be smaller
String Comparison
10
By using comparison/ relational operators
11
String Formatting
String Formatting
12
• String formatting is the process of infusing things in the string dynamically
and presenting the string
• There are four different ways to perform string formatting:
• Formatting with % Operator
• Formatting with format() string method
• Formatting with string literals, called f-strings
• Formatting with String Template Class
String Formatting
13
Formatting with % Operator
• Oldest method of string formatting
%5.3f
• Minimum number of
digits to be present in
the string.
• These might be padded
with white space if the
whole number doesn’t
have this many digits.
• Represents how many
digits are to be
displayed after the
decimal point
String Formatting
14
Formatting with % Operator
• Multiple format
conversion types in a
single print statement
String Formatting
15
Formatting with format() String Method
• Format() method was introduced with Python3 for handling complex
string formatting more efficiently
• Formatters work by putting in one or more replacement fields and
placeholders defined by a pair of curly braces { } into a string and calling
the str.format()
• The value we wish to put into the placeholders and concatenate with the
string passed as parameters into the format function.
• Benefit of this method is that we can insert object by using index-based
position
• Syntax: ‘String { } then { }’.format(‘something1′,’something2’)
String Formatting
16
Formatting with format() String Method
• We can insert
objects using
assigned
keywords
String Formatting
17
Formatting Float Precision with format() String Method
• Syntax: ‘[index]:[width][.precision][type]}
• The type can be used with format codes:
• ‘d’ for integers
• ‘f’ for floating-point numbers
• ‘b’ for binary numbers
• ‘o’ for octal numbers
• ‘x’ for octal hexadecimal numbers
• ‘s’ for string
• ‘e’ for floating-point in an exponent format
String Formatting
18
Formatting Float Precision with format() String Method
String Formatting
19
Formatting Float Precision with format() String Method
• Since, no alignment is specified, it
is aligned to the right
• Takes a width of 8 as a whole
leaving 2 places to the left.
• Fill the remaining places with zero
String Formatting
20
Formatting String with F-Strings
• To create an f-string, prefix the string with the letter “ f ”
• The string itself can be formatted in much the same way that you would
with str.format()
• F-strings provide a concise and convenient way to embed python
expressions inside string literals for formatting
String Formatting
21
Formatting String with F-Strings
• Arithmetic
operations using
F-strings
• Float Precision:
• Syntax:
{value:{width}.{precision}}
22
String Slicing
String Slicing
23
• Python slicing is about obtaining a sub-string from the given string by
slicing it respectively from start to end
• Python slicing can be done in two ways
• slice() Constructor
• Extending Indexing
String Slicing
24
• Slice() Constructor
• The slice() constructor creates a slice object representing the set of
indices specified by range(start, stop, step)
• Syntax:
• slice(stop)
• slice(start, stop, step)
• Parameters:
• start: Starting index where the slicing of object starts
• stop: Ending index where the slicing of object stops
• step: It is an optional argument that determines the increment
between each index for slicing
• Return Type: Returns a sliced object containing elements in the
given range only.
String Slicing
25
• Slice() Constructor
Index tracker for positive and negative index:
• Negative comes into considers when tracking the string in reverse.
String Slicing
26
• Slice() Constructor
• Negative comes into considers when tracking the string in reverse.
String Slicing
27
• Extending Indexing
• In Python, indexing syntax can be used as a substitute for the slice
object. This is an easy and convenient way to slice a string both
syntax wise and execution wise.
• Syntax: string[start:end:step]
String Slicing
28
• Extending Indexing
• Example
Reverse String
String Slicing
29
• Extending Indexing
• Example
String Slicing
30
• Extending Indexing
• Example
31
String Splitting
String Splitting
32
• The split() method splits a string into a list
• Syntax: string.split(separator, maxsplit)
• separator: Optional. Specifies the separator to use when
splitting the string. By default, any whitespace is a separator
• max split: Optional. Specifies how many splits to do. Defaulty
value is -1, which is “all occurrences”
String Splitting
33
• The split() method splits a string into a list
• Example:
String Splitting
34
• The split() method splits a string into a list
• Example:
String Splitting
35
• The split() method splits a string into a list
• Example:
36
String Stripping
String Stripping
37
• The strip() method removes any leading (spaces at the beginning)
and trailing (spaces at the end) characters (space is the default
leading character to remove)
• Syntax: string.strip(characters)
• characters: Optional. A set of characters to remove as leading/
trailing characters.
String Stripping
38
• Examples:
String Stripping
39
• Examples:
40
Regular Expressions: Matching, Search and replace
Regular Expression
41
• Regular Expressions, often shortened as regex, are a sequence of
characters used to check whether a pattern exists in a given text (string)
or not
• The Python module re provides full support for Perl-like regular
expressions in Python.
• Its primary function is to offer a search, where it takes a regular
expression and a string. Here, it either returns the first match or else
none.
RegEx Functions
42
MetaCharacters
43
• MetaCharacters are characters with a special meaning
[ ] - A set of Characters
MetaCharacters
44
• MetaCharacters are characters with a special meaning
[ ] - A set of Characters
MetaCharacters
45
• MetaCharacters are characters with a special meaning
 - Signals a special sequence (can also be used to escape special characters)
MetaCharacters
46
• MetaCharacters are characters with a special meaning
. - Any character (except newline character)
MetaCharacters
47
• MetaCharacters are characters with a special meaning
^ - Starts with
MetaCharacters
48
• MetaCharacters are characters with a special meaning
$ - Ends with
MetaCharacters
49
• MetaCharacters are characters with a special meaning
* - Zero or More Occurrences
MetaCharacters
50
• MetaCharacters are characters with a special meaning
+ - One or More Occurrences
MetaCharacters
51
• MetaCharacters are characters with a special meaning
? - Zero or One Occurrence
MetaCharacters
52
• MetaCharacters are characters with a special meaning
{ } - Exactly the specified number of occurrences
MetaCharacters
53
• MetaCharacters are characters with a special meaning
| - Either or
Special Sequences
54
Special Sequences
55
Special Sequences
56
Special Sequences
57
Special Sequences
58
Special Sequences
59
Special Sequences
60
Special Sequences
61
Special Sequences
62
Special Sequences
63
Special Sequences
64
Special Sequences
65
Sets
66
Sets
67
Sets
68
Sets
69
Sets
70
Sets
71
Sets
72
Example
Sets
73
Example – email
Search
74
Example – email
Replace
75
Example
Replace
76
Example
77
Patterns
Pattern
78
Pattern
79
The difference between the above two programs is space provided in third line of the
program.
Pyramid Pattern
Pattern
80
The difference between the above two programs is space provided in third line of the
program.
Pyramid Pattern
Pattern
81
Pattern
82
Pattern
83
Pattern
84
Pattern
85
Pattern
86
Pattern
87
Pattern
88
Pattern
89
Pattern
90
Floyd’s Triangle
Pattern
91
To print letter “E”
92
End of Module-5
93

More Related Content

Similar to BCSE101E_Python_Module5 (4).pdf

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulationShahjahan Samoon
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++NUST Stuff
 
Set Similarity Search using a Distributed Prefix Tree Index
Set Similarity Search using a Distributed Prefix Tree IndexSet Similarity Search using a Distributed Prefix Tree Index
Set Similarity Search using a Distributed Prefix Tree IndexHPCC Systems
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C languageMehwish Mehmood
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)Dilawar Khan
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxTinku91
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysisIffat Anjum
 
Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings | Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings | FabMinds
 
Acm aleppo cpc training ninth session
Acm aleppo cpc training ninth sessionAcm aleppo cpc training ninth session
Acm aleppo cpc training ninth sessionAhmad Bashar Eter
 
Optimizing Set-Similarity Join and Search with Different Prefix Schemes
Optimizing Set-Similarity Join and Search with Different Prefix SchemesOptimizing Set-Similarity Join and Search with Different Prefix Schemes
Optimizing Set-Similarity Join and Search with Different Prefix SchemesHPCC Systems
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3Syed Farjad Zia Zaidi
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxPRASENJITMORE2
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arraysphanleson
 
Array , Structure and Basic Algorithms.pptx
Array , Structure and Basic Algorithms.pptxArray , Structure and Basic Algorithms.pptx
Array , Structure and Basic Algorithms.pptxMrNikhilMohanShinde
 

Similar to BCSE101E_Python_Module5 (4).pdf (20)

String and string manipulation
String and string manipulationString and string manipulation
String and string manipulation
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
 
Lecture#9 Arrays in c++
Lecture#9 Arrays in c++Lecture#9 Arrays in c++
Lecture#9 Arrays in c++
 
Set Similarity Search using a Distributed Prefix Tree Index
Set Similarity Search using a Distributed Prefix Tree IndexSet Similarity Search using a Distributed Prefix Tree Index
Set Similarity Search using a Distributed Prefix Tree Index
 
Advance topics of C language
Advance  topics of C languageAdvance  topics of C language
Advance topics of C language
 
CS4443 - Modern Programming Language - I Lecture (2)
CS4443 - Modern Programming Language - I  Lecture (2)CS4443 - Modern Programming Language - I  Lecture (2)
CS4443 - Modern Programming Language - I Lecture (2)
 
STRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptxSTRINGS_IN_PYTHON 9-12 (1).pptx
STRINGS_IN_PYTHON 9-12 (1).pptx
 
Lecture 02 lexical analysis
Lecture 02 lexical analysisLecture 02 lexical analysis
Lecture 02 lexical analysis
 
Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings | Python Programming | JNTUA | UNIT 3 | Strings |
Python Programming | JNTUA | UNIT 3 | Strings |
 
Acm aleppo cpc training ninth session
Acm aleppo cpc training ninth sessionAcm aleppo cpc training ninth session
Acm aleppo cpc training ninth session
 
Optimizing Set-Similarity Join and Search with Different Prefix Schemes
Optimizing Set-Similarity Join and Search with Different Prefix SchemesOptimizing Set-Similarity Join and Search with Different Prefix Schemes
Optimizing Set-Similarity Join and Search with Different Prefix Schemes
 
Python-Basics.pptx
Python-Basics.pptxPython-Basics.pptx
Python-Basics.pptx
 
Introduction To Programming with Python-3
Introduction To Programming with Python-3Introduction To Programming with Python-3
Introduction To Programming with Python-3
 
Pointers
PointersPointers
Pointers
 
Python Basics.pptx
Python Basics.pptxPython Basics.pptx
Python Basics.pptx
 
unit1 python.pptx
unit1 python.pptxunit1 python.pptx
unit1 python.pptx
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Console I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptxConsole I/o & basics of array and strings.pptx
Console I/o & basics of array and strings.pptx
 
Strings Arrays
Strings ArraysStrings Arrays
Strings Arrays
 
Array , Structure and Basic Algorithms.pptx
Array , Structure and Basic Algorithms.pptxArray , Structure and Basic Algorithms.pptx
Array , Structure and Basic Algorithms.pptx
 

Recently uploaded

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

Recently uploaded (20)

Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

BCSE101E_Python_Module5 (4).pdf