Python Unit 3
Python Unit 3
String
A string is a sequence of characters, and it is one of the fundamental data types
used to represent text. Strings are enclosed in either single quotes (' '), double
quotes (" "), or triple quotes (''' ''', or """ """), and you can choose the style
that best fits your needs.
1. Creating Strings:
In Python, you can create strings using single quotes (' '), double quotes (" "), or
triple quotes (''' ' ''', or """ """). The choice of quotation style is flexible and
depends on your specific needs.
examples:
2. String Concatenation:
str1 = "Hello"
str2 = "World"
You can also use the += operator to update an existing string with the
concatenated value.
,
3.Properties of strings :
strings are immutable, meaning they cannot be changed after they are
created. Once a string is created, you cannot modify its contents.
However, you can create new strings based on the original string
my_string = "Hello"
# my_string[0] = 'J'
4. String Length: You can find the length of a string using the len()
function. The len() function returns the number of characters in the
string, including spaces and special characters.
You can use both positive and negative indexing, with negative indexing
counting from the end of the string.
6. Slicing Strings: String slicing allows you to extract a portion of a
string by specifying a start index, stop index (exclusive), and an optional
step value. The format for slicing is [start:stop:step].
substring2 = text[7:12:2]
print(substring2) # Wrd
You can omit the start and stop values to slice from the beginning or to
the end of the string. The step value determines how the slice progresses
through the string.
String Methods:
For example :
print(stripped_text)
print(upper_text)
# output
Hello, World!
HELLO, WORLD!
hello, world!
# Splitting a string:
sentence = "This is a sample sentence."
words = sentence.split(' ')
print(words)
# Output:
isupper():
text = "HELLO"
result = text.isupper()
print(result) # True
text = "Hello"
result = text.isalpha()
print(result) # True
number = "12345"
result = number.isdigit()
print(result) # True
Example-1:
result = my_string.endswith("World!")
result = text.startswith("Hello,", 0, 6)
print(result) # True
char = 'A'
unicode_value = ord(char)
print(unicode_value) # Output: 65
unicode_value = 65
character = chr(unicode_value)
# Replace a substring
String Formatting:
#code
n1=45
n2=46
print("first value is ",n1," and IInd is ",n2)
#output
first value is 45 and IInd is 46
name = "Alice"
age = 30
name = "Bob"
age = 25
formatted_string = "My name is {} and I am {} years old ".format(name,
age)
print(formatted_string)
# output
return True
test_string = "madam"
arr = list(test_string)
if is_palindrome(arr):
print("The string is a palindrome!")
else:
print("The string is not a palindrome.")
Q.W.A.P to Create a function to count the number of vowels and consonants
also number of digit in a given string. ?
def count_vowels_consonants(arr):
vowels = "aeiou"
consonants = "bcdfghjklmnpqrstvwxyz"
d="0123456789"
arr = arr.lower()
vowel_count = 0
consonant_count = 0
digit_count=0
c=0
index = 0
while index < len(arr):
char = arr[index]
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
elif char in d:
digit_count+=1
else:
c+=1
index += 1
return vowel_count, consonant_count,digit_count,c
test_arr = "Hello82*World&&"
result = count_vowels_consonants(test_arr)
print("actual string was ", test_arr)
print("Number of vowels:", result[0])
print("Number of consonants:", result[1])
print("Number of digit ", result[2])
print("Number of other symbols ", result[3])
# output
Test string: Hello82*World&&
Number of vowels: 3
Number of consonants: 7
Number of digit 2
Number of other symbols 3
String repetition:
List:
In Python, a list is a versatile data structure , allowing for ordered and
indexed storage. It's denoted by square brackets [ ] .
Lists are a fundamental data structure used in programming to store
collections of items. They are mutable, meaning their elements can be
modified after the list is created. Lists can contain elements of different
data types (e.g., integers, strings, other lists, etc.) and allow for various
operations like addition, removal, and modification of elements.
Creating a list:
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange", "grape"]
mixed_list = [10, "twenty", True, 3.14]
# Accessing elements by index (indexing starts at 0)
print(numbers[0]) # Output: 1
print(fruits[2]) # Output: orange
print(mixed_list[1]) # Output: twenty
# Negative indexing - accessing elements from the end of the list
print(numbers[-1]) # Output: 5 (last element)
List operations:
Concatenating lists :
List slicing is a powerful feature that allows you to extract a portion of a list by
specifying a range. The syntax for slicing is list[start:stop:step].
start: The starting index of the slice. It's inclusive, meaning the element
at this index is included in the slice.
stop: The ending index of the slice. It's exclusive, so the element at this
index is not included in the slice.
step: The increment between elements. This is an optional parameter
and defaults to 1 if not specified.
numbers = [1, 2, 3, 4, 5]
sliced_list = numbers[1:3] # Retrieves elements at index 1 and 2
print(sliced_list) # Output: [2, 3]
List methods:
join(): join() method in Python is used to concatenate elements of an
iterable (like a list) into a single string. It joins each element of the
iterable with a specified separator string.
separator = “”
result = separator.join(my_list)
example-2
separator = "_"
result = separator.join(my_list)
print(result) # mango_banana_orange
enumerate():
enumerated_list = list(enumerate(my_list))
print(enumerated_list)
#output
The in keyword returns True if the value is found in the sequence and
False otherwise. It's a convenient way to check for membership and is
commonly used in conditional statements or loops for decision-making
based on the presence or absence of a particular element within a
sequence.
Example :
my_list = [1, 2, 3, 4, 5]
is_in_list = 3 in my_list
is_in_list = 10 in my_list
Example-1 using if :
my_list = [1, 2, 3, 4, 5]
if 3 in my_list:
Example-2 using if :
Example-3 using if :
if "world" in my_string:
Example-4 using if :
if 20 in my_tuple:
Dictionary:
dictionaries are another fundamental data structure in programming
languages like Python. They are used to store data in the form of key-
value pairs, allowing efficient retrieval of values based on keys.
Dictionaries are mutable and versatile, providing a way to associate
unique keys with corresponding values.
Creating a dictionary:
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"email": "[email protected]"}
# Accessing values using keys
print(person["name"]) # Output: Alice
print(person["age"]) # Output: 30
# Using the get() method to access values with fallback option
print(person.get("city")) # Output: New York
print(person.get("job", "Not specified")) # Output: Not specified (fallback
value)
person = {
"name": "Alice",
"age": 30,
"city": "New York",
"email": [email protected]}
# Modifying values in a dictionary
person["age"] = 32 # Changing the value of the "age" key
print(person) # Output: Updated dictionary with modified age
# Adding new key-value pairs
person["job"] = "Engineer"
print(person) # Output: Updated dictionary with the new "job" key
To remove an element from a dictionary in Python, you can use the del
keyword or the pop() method.
del my_dict['b']
example-2
my_dict.pop('b')
Dictionary Methods:
tuple :
A tuple is a data structure in Python that is quite similar to a list, but with
one major difference: it's immutable. Once you create a tuple, you can
not change its elements. Tuples are created by enclosing comma-
separated values within parentheses.
Example :
my_tuple = (1, 2, 'hello', 3.14)
print(my_tuple[2]) # Accesses the third element ('hello')
Data Integrity: Tuples are used when you want to ensure that the data
remains constant throughout the program execution.
Return Multiple Values: Functions can return multiple values as a tuple,
which can be unpacked by the caller.
Dictionary Keys: Tuples are hashable and can be used as keys in
dictionaries, unlike lists which are mutable and thus cannot be used as
keys.
Methods of tuple :
count()
Counts the number of occurrences of a specified element in the tuple.
Example:
my_tuple = (1, 2, 2, 3, 2, 4)
count_of_twos = my_tuple.count(2) # Returns 3
index()
Finds the index of the first occurrence of a specified value in the tuple.
Example:
my_tuple = ('a', 'b', 'c', 'a')
index_of_a = my_tuple.index('a') # Returns 0 (index of first 'a')
len()
Returns the number of elements in the tuple.
Example:
my_tuple = (1, 2, 3, 4)
length = len(my_tuple) # Returns 4
sorted()
Returns a new list containing all elements from the tuple in sorted
order (does not modify the original tuple as tuples are immutable).
Example:
my_tuple = (4, 1, 3, 2)
sorted_tuple = sorted(my_tuple) # Returns [1, 2, 3, 4]
max() and min()
Returns the maximum or minimum element in the tuple.
Example:
my_tuple = (10, 30, 20, 5)
max_value = max(my_tuple) # Returns 30
min_value = min(my_tuple) # Returns 5
For example:
Function:
A function is a named block of code that performs a specific task or a set of
tasks. Functions are a fundamental concept in programming and are used to
organize code into reusable and modular units.
# Function body
# Code to perform the task
def xyz(name):
message = xyz("ajay")
In this example, the xyz function takes a name as a parameter and returns a
value in message object .
Functions are a powerful way to make your code more organized, reusable, and
easier to, as they allow you to encapsulate specific functionality into separate
units.
def even_numbers(num):
even_numbers(10)
1. Built-in Functions:
These functions are part of the Python standard library and are
available for use without the need for additional imports.
Examples include print(), len(), type(), int(), str(), and
list().
2. User-Defined Functions:
These functions are defined by the programmer to perform specific
tasks.
You create these functions using the def keyword.
Example:
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message) # Output: Hello, Alice!
3. Lambda Functions (Anonymous Functions):
Lambda functions are small, anonymous functions defined using the
lambda keyword.
They are often used for simple, one-liner operations and can be
passed as arguments to other functions.
Example :
double = lambda x: x * 2
result = double(5)
print(result) # Output: 10
4. Recursive Functions:
Recursive functions are functions that call themselves to solve a
problem.
They are often used for tasks that can be broken down into smaller,
similar subtasks.
Example: A recursive function to calculate the factorial of a number.
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
result = factorial(5)
print(result) # Output: 120
5. Higher-Order Functions:
These functions take one or more functions as arguments or return
functions as results.
Examples include map(), filter(), and reduce(), which operate
on iterable data structures and apply a given function to their
elements.
6. Pure Functions:
Pure functions are functions that have no side effects and always
return the same output for the same input.
They do not modify external variables or have other hidden effects.
Pure functions are important in functional programming.
7. Generator Functions:
Generator functions use the yield keyword to create iterable
sequences of values.
They generate values on-the-fly and are memory-efficient for
handling large data sets.
Example: Creating a generator with a yield statement.
8. Decorator Functions:
Decorators are functions that modify the behavior of other functions
or methods.
They are often used to add additional functionality to existing
functions without modifying their code.
Example: Creating a custom decorator to log function calls.
9. Class Methods and Instance Methods:
Functions defined within classes are called methods. There are two
main types:
Class methods are defined using the @classmethod
decorator and work on the class itself.
Instance methods are defined without any special decorator
and operate on instances of the class.
10. Special Methods (Magic Methods):
Special methods are identified by double underscores (e.g.,
__init__, __str__, __add__) and are used to define how objects of
custom classes behave when certain operations are performed on
them.
import statement :
the import statement is used to include external modules or libraries, which
are collections of functions and variables in Python program. These modules
provide additional functionality that is not available in the Python standard
library.
import math
x = math.sqrt(16)
pi_value = math.pi
import math as m
# Calculate the square root of a number using the alias 'm'
x = m.sqrt(25)
print(x)
x = sqrt(9)
print(x) # Output: 3.0