0% found this document useful (0 votes)
2 views32 pages

Python String Basics and Operations

This document provides an overview of strings in Python, covering their definition, declaration, indexing, and traversal. It also discusses string formatting, built-in string methods, operations, and the use of regular expressions for string manipulation. Key concepts include string immutability, various string operations, and the use of the 're' module for pattern matching.

Uploaded by

ssp13122007
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)
2 views32 pages

Python String Basics and Operations

This document provides an overview of strings in Python, covering their definition, declaration, indexing, and traversal. It also discusses string formatting, built-in string methods, operations, and the use of regular expressions for string manipulation. Key concepts include string immutability, various string operations, and the use of the 're' module for pattern matching.

Uploaded by

ssp13122007
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

MODULE 4 PART 2: STRINGS

MALAVIKA M HARI

MVJ College Of Engineering

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 1 / 31


Strings

The Python string data type is a sequence made up of one or more


individual characters, where a character could be a letter, digit,
whitespace, or any other symbol.
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.
Multiple ways to declare strings:
name = "India"
country = name
graduate = ’N’
nationality = str("Indian")

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 2 / 31


String Indexing and Travesal

Individual characters in a string are accessed using the subscript


(index) operator [ ].
The index specifies the position of a character we want to access.
The index of the first character is 0 and the last character is n − 1,
where n is the total number of characters.
If we try to exceed the bounds (below 0 or above n − 1), Python
raises an IndexError.
A string can be traversed by accessing characters from one index to
another.
In Python, strings are immutable, meaning once a string is created,its
individual characters cannot be changed or modified using indexing.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 3 / 31


String Indexing and Travesal

message = "Hello!"
index = 0
for i in message:
print("message[", index, "] =", i)
index += 1
Output
message[ 0 ] = H
message[ 1 ] = e
message[ 2 ] = l
message[ 3 ] = l
message[ 4 ] = o
message[ 5 ] = !
Trying to access message[7] generates an IndexError.
Even whitespace, punctuation, and special characters have their own index
positions.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 4 / 31


STRING FORMATTING OPERATOR
In Python, the % operator is used for string formatting. It allows us to
construct strings by replacing parts of the string with the data stored in
variables. The general syntax is:

”FORMAT” % (VALUES)

name = "Aarish"
age = 8

print("Name = %s and Age = %d" %(name, age))


print("Name = %s and Age = %d" %("Anika", 6))
OUTPUT:
Name = Aarish and Age = 8
Name = Anika and Age = 6
If the number of format specifiers and the number of values do not match,
Python raises an error.
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 5 / 31
STRING FORMATTING OPERATOR

Format Symbol Purpose


%c Character
%d or %i Signed decimal integer
%s String
%u Unsigned decimal integer
%o Octal integer
%x or %X Hexadecimal integer (x–lowercase, X–uppercase)
%e or %E Exponential notation
%f Floating point number
%g or %G Shortest representation (float or exponential)

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 6 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 7 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 8 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 9 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 10 / 31


Build in String Methods and Functions

"HELLO"

hello

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 11 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 12 / 31


Build in String Methods and Functions

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 13 / 31


String Operations in Python

1. Concatenation (+):Used to join two strings.

s1 = "Hello"
s2 = "World"
print(s1 + s2)

Output:

HelloWorld

[Link] (*):Used to repeat a string multiple times.

s = "Hi "
print(s * 3)

Output:

Hi Hi Hi
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 14 / 31
String Operations in Python
3. Indexing: Accessing characters using index (starting from 0).
s = "Python"
print(s[0])
print(s[3])
Output:
P
h
4. Slicing: Extracting part of the string using string[start:end].
s = "Python"
print(s[0:3])
Output:
Pyt
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 15 / 31
String Operations in Python
Slicing eg:

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 16 / 31


String Operations in Python
5. Membership Operations (in, not in): Operators (in, not in) used
to check whether a character or substring exists in a string.
print("py" in "python")
print("hi" not in "hello")
Output:
True
True
6. Length of String: Finding number of characters using len().
s = "hello"
print(len(s))
Output:
5
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 17 / 31
String Operations in Python
7. ord() and chr()
The ord() function returns the ASCII (or Unicode) code of a given
character, and the chr() function returns the character represented by an
ASCII (or Unicode) number. The ASCII values of ’A’-’Z’ are 65–90 and
’a’-’z’ are 97–122.

ch = ’A’
print(ord(ch))

Output:

65

print(chr(65))

Output:

A
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 18 / 31
Comparing Strings
Python allows you to compare strings using relational (comparison)
operators such as >, <, ==, !=, <=, >=, etc. Python compares strings using
ASCII order. The ASCII values of ’A’-’Z’ are 65–90 and ’a’-’z’ are 97–122.
Operator Description Example
== If two strings are equal, returns True. "ABC" == "ABC"
⇒ True
!= or <> If two strings are not equal, returns "ABC" != "Abc"
True. ⇒ True
> True if the first string is greater than "abc" > "ABC"
the second. ⇒ True
< True if the second string is greater "abc" < "abcd"
than the first. ⇒ True
>= True if the first string is greater than "ABC" >= "ABC"
or equal to the second. ⇒ True
<= True if the second string is greater "ABC" <= "ABc"
than or equal to the first. ⇒ True
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 19 / 31
Iterating a String

A string is a sequence type (a sequence of characters). You can iterate


through the string using a for loop or a while loop.
Example 6.19: Iterating a string using for loop

str = "Welcome to Python"


for i in str:
print(i, end=’ ’)

Output:

W e l c o m e t o P y t h o n

In this program, the for loop executes once for every character in the
string. Iteration starts from the first character and ends at the last
automatically.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 20 / 31


Iterating a String

Example 6.20: Iterating a string using while loop

message = "Welcome to Python"


index = 0

while index < len(message):


letter = message[index]
print(letter, end=’ ’)
index += 1

Output:

W e l c o m e t o P y t h o n

In this program, iteration happens using the index of each character. The
loop condition index < len(message) ensures the loop runs until the
last character’s index is reached.
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 21 / 31
Program

string = input("Enter a string : ")

ch = input("Enter the character to be searched : ")

count = 0

for c in string:

if c == ch:

count += 1

print("The character '", ch, "' occurs ", count ,"times")

The character e occurs 2 times

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 22 / 32


Program
Program to find the frequency of characters, words , lines in text.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 23 / 32


String Module

The string module consists of useful constants, classes and functions


used to manipulate strings. These constants help in character
classification.
String Module Constants
The string module in Python provides several predefined constants
that represent groups of characters such as alphabets, digits,
punctuation, etc.
These constants are useful in string processing, validation, and text
classification.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 24 / 32


String Module Constants

The string module constants are predefined constants that represent


groups of characters such as alphabets, digits, punctuation, etc.
[Link] letters – Combination of lowercase and uppercase
letters.
[Link] lowercase – All lowercase letters a –z.
[Link] uppercase – All uppercase letters A–Z.
[Link] – Digits 0–9.
[Link] – Hex digits 0–9, a–f, A–F.
[Link] – Octal digits 0–7.
[Link] – ASCII punctuation characters.
[Link] – Digits, letters, punctuation, whitespace.
[Link] – Characters like space, tab, newline, return,
form-feed, vertical-tab.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 25 / 32


String Module Constants
import string
print("ASCII Letters :", string.ascii_letters)
print("Lowercase Letters :", string.ascii_lowercase)
print("Uppercase Letters :", string.ascii_uppercase)
print("Digits :", [Link])
print("Hex Digits :", [Link])
print("Octal Digits :", [Link])
print("Punctuation :", [Link])

ASCII Letters : abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP


Lowercase Letters : abcdefghijklmnopqrstuvwxyz
Uppercase Letters : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Digits : 0123456789
Hex Digits : 0123456789abcdefABCDEF
Octal Digits : 01234567
Punctuation : !"#$%&’()*+,-./:;<=>?@[\]^_‘{|}~
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 26 / 32
Regular Expressions

Regular expressions (RE) are a powerful tool used for searching and
manipulating strings.
Python provides support for regular expressions through the re
module.
A regular expression is a sequence of characters that defines a search
pattern.

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 27 / 32


[Link]() Function
The [Link]() function attempts to match a pattern only at the
beginning of the string.
[Link](pattern, string, flags=0)

Note: match() returns a match object on success, otherwise None.


MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 28 / 32
[Link]() Function
The search() function looks for a pattern anywhere in the string.

[Link](pattern, string, flags=0)


Example Program

import re
string = "She sells sea shells on the sea shore"
pattern = "sells"

if [Link](pattern, string):
print("Match Found")
else:
print(pattern, "is not present in the string")

Output

Match Found
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 29 / 32
[Link]() Function
The sub() function replaces occurrences of a pattern in a string with a
replacement string.

[Link](pattern, repl, string, max=0)


Example Program

import re
string = "She sells sea shells on the sea shore"
pattern = "sea"
repl = "ocean"
new_string = [Link](pattern, repl, string, 1)
print(new_string)

Output

She sells ocean shells on the sea shore

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 30 / 32


[Link]()Function

The findall() function returns a list of all matching substrings.

[Link](pattern, string, flags=0)


Example

import re
pattern = r"[A-Za-z]+\d+"
matches = [Link](pattern,
"LXI 2013, VXI 2015, VDI 20104")
print(matches)

Output

[’LXI2013’, ’VXI2015’, ’VDI20104’]

MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 31 / 32


[Link]()Function
The finditer() function returns an iterator yielding match objects.

[Link](pattern, string, flags=0)


Example
import re
pattern = r"[A-Za-z]+\d+"
matches = [Link](pattern,
"LXI 2013 VXI 2015 VDI 20104")
for match in matches:
print("Match found at starting index :", [Link]())
print("Match found at ending index :", [Link]())
print("Span :", [Link]())
Output (sample)
Match found at starting index : 0
Match found at ending index : 8
Span : (0, 8)
MALAVIKA M HARI (MVJ College Of Engineering) MODULE 4 PART 1 32 / 32

You might also like