0% found this document useful (0 votes)
3 views

Python Unit - 3( a )String

This document is an introduction to Python programming focused on string data types and operations. It covers string characteristics, manipulation methods, and practical examples, including quizzes and assignments for assessment. The learning objectives aim to equip students with the skills to understand and manipulate strings effectively in Python.

Uploaded by

vinitathanvi4clg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Unit - 3( a )String

This document is an introduction to Python programming focused on string data types and operations. It covers string characteristics, manipulation methods, and practical examples, including quizzes and assignments for assessment. The learning objectives aim to equip students with the skills to understand and manipulate strings effectively in Python.

Uploaded by

vinitathanvi4clg
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

CSA 6007T

INTRODUCTION TO PYTHON
PROGRAMMING
BCA – II YEAR
IV SEMESTER

By:-
Vinita Thanvi
Assistant Professor
Lucky Institute of Professional Studies

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
Python Complex Data Types:
Using String Data Type and String Operations
Understanding String Manipulation, Methods,
and Programmatic Use

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Outline

1.Introduction to String Data Type in Python


2.String Operations and Manipulation Methods
3.Common String Methods
4.Working with String Indexing and Slicing
5.Programs Using Strings
6.Summary
7.Assessment (Quiz)
8.Assignment

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Learning Objectives

•Understand the string data type in Python.


•Learn how to manipulate strings using Python’s built-in
methods.
•Understand string operations like concatenation, repetition,
and searching.
•Learn string slicing and indexing to access specific parts of a
string.
•Implement practical programs using string data types.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Introduction to String Data Type in Python

•A string is a sequence of characters.


•It is one of Python’s built-in data types.
•Strings are immutable, meaning their value cannot be changed after
creation.
•Declaration: Strings can be declared using single quotes (' ') or double
quotes (" ").
•This includes letters, numbers, and symbols.
•Python has no character data type so single character is a string of
length 1.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Basic Characteristics of Strings in Python

1.Immutable: Strings in Python are immutable, meaning once a string is


created, its value cannot be changed. Any modification results in the
creation of a new string.
•Example:
s = "Hello"
s[0] = "h" # This will raise a TypeError

2.Sequence of Characters: A string is a sequence of characters (letters,


numbers, symbols, spaces) and can be indexed, sliced, and iterated over.

3.String Representation: Python strings are represented as objects of the


str class. Every string has some associated methods and properties.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Example:

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Creating a String

 Strings can be created using either single (‘) or double (“) quotes.
 EXAMPLE:
s1 = ‘vinita'
s2 = “VINITA"
print(s1)
print(s2)

 Output
vinita
VINITA

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (”’ or “””).

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


 Accessing characters in Python String

 Strings in Python are sequences of characters, so we can access


individual characters using indexing. Strings are indexed starting
from 0 and -1 from end. This allows us to retrieve specific characters
from the string.
 Note: Accessing an index out of range will cause an IndexError. Only
integers are allowed as indices and using a float or other types will
result in a TypeError.
 Python allows negative address references to access characters from
back of the String, e.g. -1 refers to the last character, -2 refers to the
second last character, and so on.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
String Slicing

 Slicing is a way to extract portion of a string by specifying the start and end
indexes.
 The syntax for slicing is string[start:end], where start starting index and end
is stopping index (excluded).
 String slicing allows you to extract a portion (substring) of the string using
the : operator.
 The syntax :
string[start:end]
start: The starting index (inclusive).
end: The ending index (exclusive).

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
Skipping characters with slicing:
 You can also use a step in slicing:

#(every second character)

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Example:

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


String Immutability
Strings in Python are immutable. This means that they cannot be changed
after they are created. If we need to manipulate strings then we can use
methods like concatenation, slicing, or formatting to create new strings
based on the original.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Deleting a String
 In Python, it is not possible to delete individual characters from a string
since strings are immutable.
 However, we can delete an entire string variable using the del keyword.
 Note: After deleting the string using del and if we try to access s then it will
result in a NameError because the variable no longer exists.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Updating a String
To update a part of a string we need to create a new string since
strings are immutable.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


String Operations in Python

1.Concatenation: Joining strings together using the + operator.


•Example: str1 + str2
•s1 = "Hello"
•s2 = "World"
•s3 = s1 + " " + s2
•print(s3)

•Output
•Hello World

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


2.Repetition: Repeating a string multiple times using the * operator.
•Example: "Python " * 3
•s = "Hello "
•print(s * 3)

•Output
•Hello Hello Hello

3.Length: Get the length of a string using len().


•Example: len("Python")
•s = “Vinita"
•print(len(s))

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


4. Comparison: Compare strings using relational operators.
Example:
s1 = "apple"
s2 = "banana"
# "apple" is not equal to "banana", therefore it is False
print(s1 == s2)

# "apple" is different from "banana", therefore it is True


print(s1 != s2)

# "apple" comes before "banana" lexicographically, therefore it is True


print(s1 < s2)

Output
False
True
True By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
String Manipulation Methods

1..lower(): Converts all characters to lowercase.


•Example: "HELLO".lower() → "hello"
2..upper(): Converts all characters to uppercase.
•Example: "hello".upper() → "HELLO"
3..capitalize(): Capitalizes the first letter of the string.
•Example: "hello".capitalize() → "Hello"
4..replace(old, new): Replaces a substring with another.
•Example: "hello world".replace("world", "Python") → "hello Python"
5..strip(): Removes whitespace from both ends.
•Example: " hello ".strip() → "hello"
6..split(): Splits the string into a list based on a delimiter.
•Example: "apple,banana,cherry".split(",") → ['apple', 'banana', 'cherry']

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


String Manipulation Methods

 In Python, strings are immutable sequences of characters, and there are many
built-in methods for manipulating and handling strings.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
1. Basic String Methods:

•len(s): Returns the length of the string s.

s = "Hello" print(len(s)) # Output: 5

•str.upper(): Converts the string to uppercase.

s = "hello" print(s.upper()) # Output: "HELLO“

•str.lower(): Converts the string to lowercase.

s = "HELLO" print(s.lower()) # Output: "hello"

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


•str.capitalize(): Capitalizes the first character of the string and makes the rest
lowercase.

s = "hello" print(s.capitalize()) # Output: "Hello"


•str.title(): Capitalizes the first letter of each word in the string.

s = "hello world" print(s.title()) # Output: "Hello World"


•str.swapcase(): Swaps uppercase letters to lowercase and vice versa.

s = "HeLLo WoRLd" print(s.swapcase()) # Output: "hEllO wOrlD"

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


•str.strip(): Removes any leading and trailing whitespace from the string.

s = " Hello " print(s.strip()) # Output: "Hello"


•str.replace(old, new): Replaces all occurrences of the substring old with new.

s = "Hello World" print(s.replace("World", "Python")) # Output: "Hello Python"


•str.split(sep): Splits the string into a list of substrings based on the separator
sep.

s = "apple,banana,cherry" print(s.split(',')) # Output: ['apple', 'banana', 'cherry']


•str.join(iterable): Joins the elements of an iterable (e.g., list) into a single
string, using the string as a separator.

s = "-" seq = ("a", "b", "c") print(s.join(seq)) # Output: "a-b-c"

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


2. Searching and Finding Substrings:
•str.find(sub): Returns the lowest index in the string where the substring sub is found, or -1 if
not found.

s = "Hello" print(s.find("e")) # Output: 1


•str.index(sub): Similar to find() but raises a ValueError if the substring is not found.

s = "Hello" print(s.index("e")) # Output: 1


•str.count(sub): Returns the number of non-overlapping occurrences of the substring sub.

s = "Hello Hello" print(s.count("Hello")) # Output: 2


•str.startswith(prefix): Returns True if the string starts with the specified prefix.

s = "Hello" print(s.startswith("He")) # Output: True


•str.endswith(suffix): Returns True if the string ends with the specified suffix.

s = "Hello" print(s.endswith("lo")) # Output: True

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


3. String Formatting:
•str.format(): Formats a string by inserting values at specific placeholders.

name = "Alice" age = 30 print("Name: {}, Age: {}".format(name, age))


# Output: "Name: Alice, Age: 30"

•f-strings (formatted string literals): A concise and efficient way to embed


expressions inside string literals.

name = "Alice" age = 30 print(f"Name: {name}, Age: {age}")


# Output: "Name: Alice, Age: 30"

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


4. String Testing:
•str.isalpha(): Returns True if all characters in the string are alphabetic.

s = "Hello" print(s.isalpha()) # Output: True

•str.isdigit(): Returns True if all characters in the string are digits.

s = "1234" print(s.isdigit()) # Output: True

•str.islower(): Returns True if all characters in the string are lowercase.


s = "hello" print(s.islower()) # Output: True

•str.isupper(): Returns True if all characters in the string are uppercase.


s = "HELLO" print(s.isupper()) # Output: True
•str.isspace(): Returns True if all characters in the string are whitespaces.
s = " " print(s.isspace()) # Output: True
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
5. Advanced Methods:
•str.zfill(width): Pads the string with zeros (0) from the left until the string reaches the specified
width.

s = "42" print(s.zfill(5)) # Output: "00042"


•str.rjust(width): Pads the string with spaces on the left until the string reaches the specified
width.

s = "Hello" print(s.rjust(10)) # Output: " Hello"


•str.ljust(width): Pads the string with spaces on the right until the string reaches the specified
width.
s = "Hello" print(s.ljust(10)) # Output: "Hello "
•str.partition(sep): Splits the string into a 3-tuple (head, sep, tail) at the first occurrence of the
separator.

s = "apple,banana,cherry" print(s.partition(',')) # Output: ('apple', ',', 'banana,cherry')


•str.rfind(sub): Returns the highest index in the string where the substring sub is found, or -1 if not
found.
s = "apple,banana,apple" print(s.rfind("apple")) # Output: 12
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS
6. Escaping Special Characters:
•str.encode(): Encodes the string into bytes using a specified encoding
(default is UTF-8).

s = "Hello" print(s.encode()) # Output: b'Hello’

•str.decode(): Decodes the bytes back to a string using the specified


encoding.

b = b"Hello" print(b.decode()) # Output: "Hello"

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Summary:

•Strings are sequences of characters in Python that allow for


indexing, slicing, and various built-in methods.
•String operations include concatenation, repetition, and
formatting.
•String manipulation methods like upper(), strip(), find(), and
replace() make working with strings flexible and easy.

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Quiz (Assessment)

1.What is the result of the following code?


python
text = "Programming" print(text[3:7])
a) "gram"
b) "Pro"
c) "gramm"
d) "ogram“

2.Which of the following methods removes whitespace from


both ends of a string? a) split()
b) strip()
c) join()
d) replace()

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


3.What will be the output of the following code?

sentence = "Welcome to Python!"


print(sentence.replace("to", "in"))
a) "Welcome in Python!"
b) "Welcome to Python!"
c) "income to Python!"
d) Error

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Practical Example:

•Program: String manipulation to reverse a string and count occurrences


of a specific character.

input_string = "Hello Python"


reversed_string = input_string[::-1]
print("Reversed:", reversed_string)
print("Occurrences of 'o':", input_string.count('o'))

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Assignments

1.Create a Python program that takes a string as input and prints


the string in reverse, along with the number of vowels in the string.

2.Write a Python function that takes a string and returns the string
with each word capitalized (capitalize every first letter of each
word).

By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS


Thank You
By: Mrs. Vinita Thanvi Assistant Professor, IT Department, LIPS

You might also like