0% found this document useful (0 votes)
5 views29 pages

Unit 2 Python Strings

This document covers the fundamentals of functions and modules in Python, focusing on string operations and regular expressions. It explains string indexing, concatenation, immutability, and built-in string methods, along with the use of regular expressions for pattern matching. Key functions such as match(), search(), and sub() are introduced, highlighting their syntax and differences.

Uploaded by

23eg104c53
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views29 pages

Unit 2 Python Strings

This document covers the fundamentals of functions and modules in Python, focusing on string operations and regular expressions. It explains string indexing, concatenation, immutability, and built-in string methods, along with the use of regular expressions for pattern matching. Key functions such as match(), search(), and sub() are introduced, highlighting their syntax and differences.

Uploaded by

23eg104c53
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit-1

Chapter II

Functions and Modules

Dr. Rajesh Thumma


Associate Professor
Department of ECE
Syllabus
 Unit-II Strings and Regular Expressions:
String Operations, Built-in String Methods and
Functions, Comparing Strings, function in
Regular Expression.
Sequence: List, Tuples, Dictionaries, Sets.
Introduction to Strings

A Python function is a block of organized, reusable code


that is used to perform a single, Specific and well defined
task .
Functions provide better modularity for your application and
a high degree of code reusing.
Reduces redundancy (repetition of the same code or logic
multiple times in a program.)
Improves modularity (dividing a program into smaller,
independent, reusable parts)
Defined using def keyword
Indexing in Strings

Indexing in Python Strings – Explanation


 What is Indexing?
• Indexing is used to access individual characters in a string.
• Python uses the subscript operator [] for indexing.
What is an Index?
• The number written inside the square brackets [ ] is called an index.
• An index tells Python which character position we want to access from the string.
• A string is an ordered collection of characters, so each character has a fixed position.
 Index Positions
• The first character in a string always has index 0
• The last character has index n − 1
Here, n = total number of characters in the string
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.

message = "Hello!"
index = 0
for i in message:
print("message[", index, "] = ", i)
index += 1

5
CONCATENATING, APPENDING
& MULTIPLYING STRINGS

CONCATENATING MULTIPLYING STRINGS


str = "Hello"
str1 = "Hello " print(str * 3)
str2 = "World"
str3 = str1 + str2
print("The concatenated string is : ", str3)

APPENDING

str = "Hello, "


name = input("\n Enter your name : ")
str += name
str += ". Welcome to Python
Programming."
print(str)

6
Example Programs

print("Hello") print("Hello". End = " ")


print("World") print("World")
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

© Oxford University Press 2017. All rights reserved. 10


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. 11


BUILT-IN STRING METHODS AND FUNCTIONS

© Oxford University Press 2017. All rights reserved. 12


BUILT-IN STRING METHODS AND FUNCTIONS

© Oxford University Press 2017. All rights reserved. 13


BUILT-IN STRING METHODS AND FUNCTIONS

© Oxford University Press 2017. All rights reserved. 14


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. 15


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. 16


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. 17


COMPARING STRINGS

© Oxford University Press 2017. All rights reserved. 18


ITERATING STRING

String is a sequence type (sequence of characters). You can iterate through


the string using for loop

© Oxford University Press 2017. All rights reserved. 19


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. 20


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
© Oxford University Press 2017. All rights reserved. 21
As the name suggest, the match() function matches a pattern to string with
EXAMPLE- Match() Function

© Oxford University Press 2017. All rights reserved. 22


The search Function

search(), in the re module that searches for a pattern anywhere in the string. The
syntax of the search() function can be given as,
[Link](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. 23


Key Differences
Feature Search Regular Expressions
Looks for exact matches or Matches patterns with complex
Purpose
substrings. rules.
Advanced string processing and
Usage Simple substring operations.
pattern matching.
Module Requirement No special module needed. Requires the re module.
Highly flexible; supports
Flexibility Limited to exact string matches. wildcards, quantifiers, and
groups.
Faster for simple substring May be slower due to pattern
Performance
searches. matching complexity.
r"a.c" matches "abc", "a1c", but
Example Match "abc" in "abcdef" → True
not "ac".
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,
[Link](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. 25


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 [Link] — Ignores case of characters, so "Match", "MATCH",
"mAtCh", etc are all same
re.S or [Link] — Enables dot (.) to match newline. By default, dot matches
any character other than the newline character.
re.M or [Link] — 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 © Oxford
or University
[Link]- Makes
Press 2017. All rights reserved. the flag \w to match all characters
26 that are
considered letters in the given current locale settings.
META CHARACTERS IN REGULAR EXPRESSION

© Oxford University Press 2017. All rights reserved. 27


META CHARACTERS IN REGULAR EXPRESSION

© Oxford University Press 2017. All rights reserved. 28


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. 29

You might also like