0% found this document useful (0 votes)
8 views19 pages

Python Unit 2

Uploaded by

karkuvelraj790
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)
8 views19 pages

Python Unit 2

Uploaded by

karkuvelraj790
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
You are on page 1/ 19

UNIT- 2

Python String:
A string is a sequence characters.Python treats anything inside quotes as a
string.This includes letters,numbers and symbols.Python has no character data type so single
character is a string of length 1.

Example: s = "ABC"
print(s[1]) # access 2nd char
s1 = s + s[0] # update
print(s1) # print
Output:

ABCA

Create a string:
Strings can be created using either single(‘) or double(“) quotes.

s1 = 'Hello'

s2 = "World"

print(s1) # O/P: Hello

print(s2) # O/P: World


Access String :

Index (Positive) → 0 1 2 3 4 5
Characters → P Y T H O N
Index (Negative) → -6 -5 -4 -3 -2 -1

Indexing:

Each character in a string has an index

Example: text = "Python"

# Index: 0 1 2 3 4 5

# 'P','y','t','h','o','n'

-Positive Indexing (starts from 0):

Example: text[0] #’P’

text[1] #’y’

-Negative Indexing (starts from -1 at the end)

Example: text[-1] # 'n'

text[-2] # 'o'

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.

Example: s = "PythonProgramming"

# Retrieves characters from index 1 to 3


print(s[1:4])

# Retrieves characters from beginning to index 2


print(s[:3])

# Retrieves characters from index 3 to the end


print(s[3:])

# Reverse the string


print(s[::-1])

Output: yth
Pyt
honProgramming
gnimmargorPnohtyP

Concatenation:

 Joining two or more strings using the + operator.


 Using the join() method for efficient concatenation of elements
from an iterable (e.g., a list of strings) with a specified separator.

Example: s1 = "Hello"

s2 = "World"

concatenated_string = s1 + " " + s2 # Using + operator

print(concatenated_string)

words = ["Python", "is", "fun"]

joined_string = " ".join(words) # Using join() method

print(joined_string)

Repetition:

 Repeating a string multiple times using the * operator.


Example: repeated_string = "Hi!" * 3

print(repeated_string)

Python String Methods:


Python string methods are built-in operations that can be called
on string objects to perform specific tasks, such as changing the case, searching, replacing, formatting,
or analyzing string contents.

They do not modify the original string, since strings in Python are immutable. Instead, they return a
new string or value as the result.The methods are,

Method Description Example Output


capitalize() Capitalizes first "hello".capitalize() 'Hello'
character
casefold() Lowercases string "HELLO".casefold() 'hello'
(aggressive)
center() Centers string in "hi".center(10) ' hi '
given width
count() Counts substring "banana".count("a") 3
occurrences
encode() Encodes string to "hello".encode() b'hello'
bytes
endswith() Checks if string "hello".endswith("o") True
ends with value
expandtabs() Sets tab size "a\tb".expandtabs(4) 'a b'
find() Finds first index of "hello".find("l") 2
substring
format() Formats using "Hello {}".format("World") 'Hello World'
placeholders
format_map() Formats using dict "{name}".format_map({"name": "Alice"}) 'Alice'
index() Finds index, raises "hello".index("l") 2
error if not found
isalnum() Checks if all chars "abc123".isalnum() True
are alphanumeric
isalpha() Checks if all chars "abc".isalpha() True
are letters
isascii() Checks if all chars "abc".isascii() True
are ASCII
isdecimal() Checks if all chars "123".isdecimal() True
are decimals
isdigit() Checks if all chars "123".isdigit() True
are digits
isidentifier() Checks if valid "var_1".isidentifier() True
Python identifier
islower() Checks if all chars "hello".islower() True
are lowercase
isnumeric() Checks if all chars "123".isnumeric() True
are numeric
isprintable() Checks if all chars "abc\n".isprintable() False
are printable
isspace() Checks if all chars " ".isspace() True
are whitespace
istitle() Checks if string is "Hello World".istitle() True
title case
isupper() Checks if all chars "HELLO".isupper() True
are uppercase
join() Joins iterable with ".".join(["a", "b", "c"]) 'a.b.c'
string as separator
ljust() Left-justifies string "hi".ljust(5, ".") 'hi...'
lower() Converts string to "HELLO".lower() 'hello'
lowercase
lstrip() Removes left " hello".lstrip() 'hello'
whitespace
maketrans() Creates translation str.maketrans("ae", "12") mapping for
table a→1, e→2
partition() Splits at first "a-b-c".partition("-") ('a', '-', 'b-c')
occurrence
replace() Replaces "hello".replace("l", "x") 'hexxo'
substrings
rfind() Finds last index of "hello".rfind("l") 3
substring
rindex() Finds last index, "hello".rindex("l") 3
raises error if not
found
rjust() Right-justifies "hi".rjust(5, ".") '...hi'
string
rpartition() Splits at last "a-b-c".rpartition("-") ('a-b', '-', 'c')
occurrence
rsplit() Splits from right "a,b,c".rsplit(",", 1) ['a,b', 'c']
rstrip() Removes right "hello ".rstrip() 'hello'
whitespace
split() Splits string "a,b,c".split(",") ['a', 'b', 'c']
splitlines() Splits on line "a\nb\nc".splitlines() ['a', 'b', 'c']
breaks
startswith() Checks if string "hello".startswith("h") True
starts with value
strip() Removes " hello ".strip() 'hello'
whitespace from
both ends
swapcase() Swaps case "HeLLo".swapcase() 'hEllO'
title() Capitalizes each "hello world".title() 'Hello World'
word
translate() Translates using a "apple".translate(str.maketrans("ae", "12")) '1ppl2'
map

upper() Converts string to "hello".upper() 'HELLO'


uppercase
zfill() Pads string with "42".zfill(5) '00042'
zeros on the left

Example:

s = " hello World! "

s2 = "Python is fun"

print("capitalize():", s.capitalize())

print("casefold():", "Straße".casefold()) # aggressive lowercase

print("center(30):", s.center(30, "-"))

print("count('l'):", s.count('l'))

print("encode():", s.encode())

print("endswith('! '):", s.endswith("! "))

print("expandtabs():", "Hello\tWorld".expandtabs(4))

print("find('World'):", s.find("World"))

print("format():", "Hello, {}!".format("Alice"))

print("format_map():", "Lang: {lang}, Ver: {ver}".format_map({"lang": "Python", "ver":


"3.12"}))

print("index('World'):", s.index("World"))
print("isalnum():", "Python3".isalnum())

print("isalpha():", "Hello".isalpha())

print("isascii():", "café".isascii())

print("isdecimal():", "123".isdecimal())

print("isdigit():", "123".isdigit())

print("isidentifier():", "var_1".isidentifier())

print("islower():", "hello".islower())

print("isnumeric():", "123".isnumeric())

print("isprintable():", "hello123!".isprintable())

print("isspace():", " ".isspace())

print("istitle():", "Hello World".istitle())

print("isupper():", "HELLO".isupper())

print("join():", ", ".join(["a", "b", "c"]))

print("ljust(20):", s2.ljust(20, "."))

print("lower():", s2.lower())

print("lstrip():", s.lstrip())

# maketrans() + translate()

table = str.maketrans("ae", "12")

print("translate():", "apple".translate(table))

print("partition('is'):", s2.partition("is"))

print("replace():", s2.replace("fun", "awesome"))

print("rfind('o'):", s2.rfind("o"))

print("rindex('o'):", s2.rindex("o"))

print("rjust(20):", s2.rjust(20, "."))

print("rpartition('is'):", s2.rpartition("is"))
print("rsplit():", s2.rsplit())

print("rstrip():", s.rstrip())

print("split():", s2.split())

print("splitlines():", "Line1\nLine2\nLine3".splitlines())

print("startswith(' hello'):", s.startswith(" hello"))

print("strip():", s.strip())

print("swapcase():", s.swapcase())

print("title():", s2.title())

print("upper():", s2.upper())

print("zfill(5):", "42".zfill(5))

Example:

capitalize(): hello world!

casefold(): strasse

center(30): ------- hello World! -------

count('l'): 3

encode(): b' hello World! '

endswith('! '): True

expandtabs(): Hello World

find('World'): 8

format(): Hello, Alice!

format_map(): Lang: Python, Ver: 3.12

index('World'): 8

isalnum(): True

isalpha(): True

isascii(): False
isdecimal(): True

isdigit(): True

isidentifier(): True

islower(): True

isnumeric(): True

isprintable(): True

isspace(): True

istitle(): True

isupper(): True

join(): a, b, c

ljust(20): Python is fun.......

lower(): python is fun

lstrip(): hello World!

translate(): 1ppl2

partition('is'): ('Python ', 'is', ' fun')

replace(): Python is awesome

rfind('o'): 4

rindex('o'): 4

rjust(20): .......Python is fun

rpartition('is'): ('Python ', 'is', ' fun')

rsplit(): ['Python', 'is', 'fun']

rstrip(): hello World!

split(): ['Python', 'is', 'fun']

splitlines(): ['Line1', 'Line2', 'Line3']

startswith(' hello'): True


strip(): hello World!

swapcase(): HELLO wORLD!

title(): Python Is Fun

upper(): PYTHON IS FUN

zfill(5): 00042

Python Built-in Functions for Strings:

Built-in functions in Python are globally available


functions provided by the language that can be used directly without importing any module.
When used with strings, these functions help in processing, transforming, and analyzing string
data.Those are,

Function Description Example Output


len() Returns the length of the string len("hello") 5
str() Converts a value to a string str(123) '123'
ord() Returns Unicode code of a character ord('A') 65
chr() Returns character from Unicode code chr(65) 'A'
repr() Returns printable (escaped) string repr("Hi\n") 'Hi\\n'
representation
format() Formats values into a string (also a method) format(3.14, '3.14'
".2f")
type() Returns the type of the variable type("hello") <class
'str'>

Example:
s = "Hello"
print("len():", len(s))
num = 123
print("str():", str(num))
print("ord('H'):", ord('H'))
print("chr(72):", chr(72))
print("repr():", repr(s))
name = "Alice"
age = 25
print("format():","Name:{},Age:{}".format(name, age))
print("type():", type(s))
Output:
len(): 5
str(): 123
ord('H'): 72
chr(72): H
repr(): 'Hello'
format(): Name: Alice, Age: 25
type(): <class 'str'>

Difference between Functions and Method:

Aspect Function Method


A reusable block of code defined
A function that is defined inside a class and is
Definition using def (or lambda) that can be
associated with that class’s objects.
called independently.
Exists independently, not bound to Always tied to an object (instance method) or the
Association
any object. class (class method, static method).
Instance methods receive self automatically,
First
No special first argument. class methods receive cls, static methods receive
Argument
none.
How to Call function_name(args) object_name.method_name(args)
Can be in global scope, inside
Scope Defined within a class body.
another function, or inside a module.
Can only access global variables or Can access and modify the object’s attributes (via
Data Access
those passed in. self).
Methods can be overridden in subclasses (OOP
Overriding Cannot be overridden like methods.
feature).

Example:
# Function
def say_hello(name):
print(f"Hello {name}, I am a function.")

# Class with Method


class Person:
def say_hello(self, name):
print(f"Hello {name}, I am a method.")

# Calling function (no object needed)


say_hello("Alice")

# Calling method (needs an object)


p = Person()
p.say_hello("Bob")

Output:
Hello Alice, I am a function.
Hello Bob, I am a method.
List Methods in python:
A list of strings in Python is a collection of string elements stored in a
single variable. It allows indexing, slicing, iteration, and supports modification.

Creating a list of strings in Python is easy and helps in managing


collections of text. For example, if we have names of people in a group, we can store them in a
list. We can create a list of strings by using Square Brackets [] . We just need to type the strings
inside the brackets and separate them with commas.

Example:
a = ["python", "is", "fun"]
# Printing the list
print(a)
Output:
['python', 'is', 'fun']

Using list() Function:

Another way to create a list of strings is by using the built-in list()


function. We can use list() function to convert other iterable objects (like tuples, sets, etc.) into a
list.

Example:
# Converting a tuple to a list using the list() function

b = list(("python", "is", "awesome"))


print(b)

Output:
['python', 'is', 'awesome']

Method Description Example Output


append(x) Adds a string to the end of list lst = ['a', 'b']; lst.append('c') ['a', 'b', 'c']
extend(iterable) Adds multiple strings to the lst.extend(['d', 'e']) ['a', 'b', 'c', 'd',
list 'e']
insert(i, x) Inserts string x at index i lst.insert(1, 'x') ['a', 'x', 'b', 'c',
'd', 'e']
remove(x) Removes first occurrence of lst.remove('c') ['a', 'x', 'b', 'd',
string x 'e']
pop() Removes and returns the last lst.pop() 'e', list becomes
string ['a', 'x', 'b', 'd']
clear() Removes all elements lst.clear() []
index(x) Returns index of first ['apple', 1
occurrence of string x 'banana'].index('banana')
count(x) Counts occurrences of string x ['a', 'b', 'a'].count('a') 2
reverse() Reverses the list in-place lst.reverse() ['d', 'b', 'x', 'a']
sort() Sorts strings alphabetically lst.sort() ['a', 'b', 'd', 'x']
copy() Creates a shallow copy of list copy = lst.copy() ['a', 'b', 'd', 'x']

Example:

# Create a list of strings

fruits = ["apple", "banana", "cherry"]

print("Original list:", fruits)

# 1. append(x) - Adds an item to the end

fruits.append("date")

print("After append:", fruits)

# 2. extend(iterable) - Adds multiple items


fruits.extend(["elderberry", "fig"])

print("After extend:", fruits)

# 3. insert(i, x) - Inserts at a specific index

fruits.insert(2, "blueberry")

print("After insert at index 2:", fruits)

# 4. remove(x) - Removes first occurrence of item

fruits.remove("banana")

print("After remove 'banana':", fruits)

# 5. pop([i]) - Removes and returns item at index (last if not specified)

popped_item = fruits.pop()

print("After pop:", fruits, "| Popped:", popped_item)

# 6. index(x) - Returns index of first match

index = fruits.index("cherry")

print("Index of 'cherry':", index)

# 7. count(x) - Counts occurrences of an item

count = fruits.count("apple")

print("Count of 'apple':", count)

# 8. sort() - Sorts the list alphabetically

fruits.sort()

print("After sort:", fruits)

# 9. reverse() - Reverses the list

fruits.reverse()

print("After reverse:", fruits)

# 10. copy() - Returns a shallow copy

copy_fruits = fruits.copy()
print("Copy of list:", copy_fruits)

# 11. clear() - Removes all items

fruits.clear()

print("After clear:", fruits)

Output:

Original list: ['apple', 'banana', 'cherry']

After append: ['apple', 'banana', 'cherry', 'date']

After extend: ['apple', 'banana', 'cherry', 'date', 'elderberry', 'fig']

After insert at index 2: ['apple', 'banana', 'blueberry', 'cherry', 'date', 'elderberry', 'fig']

After remove 'banana': ['apple', 'blueberry', 'cherry', 'date', 'elderberry', 'fig']

After pop: ['apple', 'blueberry', 'cherry', 'date', 'elderberry'] | Popped: fig

Index of 'cherry': 2

Count of 'apple': 1

After sort: ['apple', 'blueberry', 'cherry', 'date', 'elderberry']

After reverse: ['elderberry', 'date', 'cherry', 'blueberry', 'apple']

Copy of list: ['elderberry', 'date', 'cherry', 'blueberry', 'apple']

After clear: []

Tuple Method in Python:


A tuple of strings in Python is an immutable, ordered collection
where each element is a string. Once created, the elements and their order cannot be changed.

Example:

names = ("Alice", "Bob", "Charlie")


Here, names is a tuple, and each item inside it is a string. Python has two built-in methods that you can
use on tuples.Those are

Method Description Example Output


count(x) Count how many times x appears (1, 2, 1, 3).count(1) 2
index(x) Index of first x (1, 2, 3).index(2) 1

Example:

# Creating a tuple of strings

animals = ("cat", "dog", "elephant", "dog", "tiger")

print("Original tuple:", animals)

# 1. count(x) – Counts how many times a value appears

dog_count = animals.count("dog")

print("Count of 'dog':", dog_count)

# 2. index(x) – Returns the index of the first occurrence of a value

elephant_index = animals.index("elephant")

print("Index of 'elephant':", elephant_index)

Output:

Original tuple: ('cat', 'dog', 'elephant', 'dog', 'tiger')

Count of 'dog': 2

Index of 'elephant': 2

Difference between List and Tuple:

Feature List Tuple


Definition An ordered, mutable collection of items An ordered, immutable collection of
items
Syntax Defined with square brackets: [ ] Defined with parentheses: ( )
Mutability ✅ Can be changed after creation (add, ✅ Cannot bechanged after creation
remove, modify elements)
Methods Has many built-in methods like Has fewer methods like count(),
append(), remove(), pop() index()
Performance Slower compared to tuples Faster (because immutable)
Use Case When you need to store data that can When you need fixed data or want to
change protect it from modification
Example my_list = [1, 2, 3] my_tuple = (1, 2, 3)

Example:

# List

my_list = [1, 2, 3]

my_list[0] = 10 # Modifying allowed

my_list.append(4) # Adding allowed

print(my_list) # [10, 2, 3, 4]

# Tuple

my_tuple = (1, 2, 3)

# my_tuple[0] = 10 # ✅ Error: Tuples are immutable

print(my_tuple) # (1, 2, 3)

Output:

[10, 2, 3, 4]

(1, 2, 3)

Dictionary Methods in Python:

In Python, a dictionary is a built-in data type


used to store data in key-value pairs. Dictionary methods are built-in functions that can be called on
dictionary objects to manipulate, access, or retrieve information from the dictionary.
Characteristics:

 Keys are unique and immutable (strings, numbers, tuples).


 Values can be of any data type.
 Dictionaries are mutable (can be changed).

Method Description Example Output


get(key) Returns value for key; returns d = {'a': 1}; d.get('a') 1
None if key not found
keys() Returns all keys d.keys() dict_keys(['a'])
values() Returns all values d.values() dict_values([1])
items() Returns key-value pairs as d.items() dict_items([('a',
tuples 1)])
update(dict2) Updates dictionary with another d.update({'b': 2}) {'a': 1, 'b': 2}
dict
pop(key) Removes key and returns value d.pop('a') 1, dict becomes
{'b': 2}
popitem() Removes and returns last d.popitem() ('b', 2)
inserted pair
setdefault(k, v) Gets value if key exists, else d.setdefault('c', 3) 3, {'c': 3}
sets it to v
clear() Removes all items d.clear() {}
copy() Returns a shallow copy d2 = d.copy() Same as d
fromkeys(seq, Creates new dict from keys in dict.fromkeys(['x','y'], {'x': 0, 'y': 0}
v) seq, values all v 0)

Example:
person = {
"name": "Alice",
"city": "Delhi",
"profession": "Engineer"
}

print("get('city'):", person.get("city"))
print("keys():", person.keys())
print("values():", person.values())
print("items():", person.items())

person.update({"profession": "Developer", "age": "30"})


print("update():", person)
removed = person.pop("city")
print("pop('city'):", removed)
print("after pop():", person)

last = person.popitem()
print("popitem():", last)
print("after popitem():", person)

result = person.setdefault("gender", "female")


print("setdefault():", result)
print("after setdefault():", person)

copy_before_clear = person.copy()
person.clear()
print("clear():", person)

copy_dict = copy_before_clear.copy()
print("copy():", copy_dict)

keys = ["one", "two", "three"]


new_dict = dict.fromkeys(keys, "value")
print("fromkeys():", new_dict)

Output:
get('city'): Delhi
keys(): dict_keys(['name', 'city', 'profession'])
values(): dict_values(['Alice', 'Delhi', 'Engineer'])
items(): dict_items([('name', 'Alice'), ('city', 'Delhi'), ('profession', 'Engineer')])
update(): {'name': 'Alice', 'city': 'Delhi', 'profession': 'Developer', 'age': '30'}
pop('city'): Delhi
after pop(): {'name': 'Alice', 'profession': 'Developer', 'age': '30'}
popitem(): ('age', '30')
after popitem(): {'name': 'Alice', 'profession': 'Developer'}
setdefault(): female
after setdefault(): {'name': 'Alice', 'profession': 'Developer', 'gender': 'female'}
clear(): {}
copy(): {'name': 'Alice', 'profession': 'Developer', 'gender': 'female'}
fromkeys(): {'one': 'value', 'two': 'value', 'three': 'value'}

You might also like