0% found this document useful (0 votes)
4 views12 pages

Python Unit 3

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)
4 views12 pages

Python Unit 3

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

RENAISSANCE UNIVERSITY, INDORE

School of Computer Science


BCA/BSC III Sem

Subject: Fundamentals of Python


Unit 3

Strings in Python
In Python, a string is a sequence of characters enclosed within single (' '), double (" "), or
triple (''' ''' or """ """) quotes. Strings are immutable, meaning their contents cannot be
changed once they are created. Here are some basics about working with strings in Python:

Creating a String:

single_quoted_string = 'Hello, World!'


double_quoted_string = "Hello, World!"
triple_quoted_string = '''Hello, World!'''

Accessing Characters:
You can access individual characters in a string using indexing. Python uses zero-based
indexing.

my_string = "Hello, World!"


print(my_string[0])

# Output
Prints 'H'

Index tracker for positive and negative index:


Here, the Negative comes into consideration when tracking the string in reverse.
String slicing
String slicing in Python allows you to extract a substring (a portion of a string) by specifying a
start index and an end index within square brackets [start:end].

Example:

my_string = "Hello, World!"

# Extract a substring from index 0 to 4 (excluding 4)


substring = my_string[0:5]
print(substring)

# Output:
Hello

In Python, you can also omit the start or end index in a slice, which defaults to the beginning
or end of the string, respectively.

Example:

# Slice from the start to index 5 (excluding 5)


substring = my_string[:5]
print(substring)

# Output:
Hello

# Slice from index 7 to the end


substring = my_string[7:]
print(substring)

# Output:
World!

Slicing string [ :: ] method


In Python, indexing syntax can be used as a substitute for the slice object. This is an easy and
convenient way to slice a string using list slicing and Array slicing both syntax-wise and
execution-wise. A start, end, and step have the same mechanism as the slice() constructor.

Syntax
arr[start:stop] # items start through stop-1
arr[start:] # items start through the rest of the array
arr[:stop] # items from the beginning through stop-1
arr[:] # a copy of the whole array
arr[start:stop:step] # start through not past stop, by step
Example 1:

In this example, we will see slicing in python list the index start from 0 indexes and ending
with a 2 index(stops at 3-1=2 ).

# Python program to demonstrate String slicing

String = 'Hello'

# Using indexing sequence


print(String[:3])

#Output:
Hel

Example 2:
In this example, we will see the example of starting from 1 index and ending with a 5
index(stops at 3-1=2 ), and the skipping step is 2.

# Python program to demonstrate String slicing

String = 'Greetings'

# Using indexing sequence


print(String[1:5:2])

#Output
re

Example 3:
In this example, we will see the example of starting from -1 indexes and ending with a -12
index(stops at 3-1=2 )and the skipping step is -2.
# Python program to demonstrate String slicing

String = 'Greetings'

# Using indexing sequence


print(String[-1:-12:-2])

#Output
snteG

Example 4:
In this example, the whole string is printed in reverse order.
# Python program to demonstrate String slicing

String = 'Greetings'

# Prints string in reverse


print(String[::-1])

#Output
sgniteerG
Concatenation of strings in Python
String Concatenation is the technique of combining two strings. String Concatenation can be
done using different ways as follows:
1. Using + operator
2. Using “,” (comma)

1. Python String Concatenation using the ‘+’ Operator in Python:


It’s very easy to use the + operator for string concatenation. This operator can be used to
add multiple strings together. However, the arguments must be a string. Here,
The + Operator combines the string that is stored in the var1 and var2 and stores in another
variable var3.

Example:

str1 = "Hello"
str2 = "World"
concatenated_str = str1 + ", " + str2

#Output:
'Hello, World'

2. Concatenate Strings in Python using “, ” comma:

A comma “,” is a great alternative to string concatenation using “+”. when you want to
include single whitespace. Use a comma when you want to combine data types with single
whitespace in between.
Example:

var1 = "Welcome"
var2 = "to"
var3 = "RU"

# using comma to combine data types


# with a single whitespace.
print(var1, var2, var3)

Python Strings Immutability


Python String Immutability is the property of an object according to which we can not
change the object after we declared or after the creation of it is known as Immutability and
this Immutability in the case of the string is known as string immutability in Python.
Difference between Immutability and Mutability:

Mutable objects are those objects which can be modified after their creation of them, to
demonstrate mutability in Python we have a very popular data type which is the list.

Example:
lst = [1,2,3,4,5]
print(lst)
lst[0] = 10
print(lst)

Output:
[1, 2, 3, 4, 5]
[10, 2, 3, 4, 5]

Immutability refers to the property of an object which we cannot change after declaration.
Example 1:
my_string = "Python Programming"
# Attempt to modify the string
my_string[0] = ‘p’
# Raises TypeError: 'str' object does not support item assignment
# this will give an typeError

Example 2:
str1 = "Hello world"
[Link]('H', 'h')
print(str1)

Output:
Hello world

String functions/methods in Python:


1. String Length: You can find the length of a string using the len() function.
2. lower(): Converts all uppercase characters in a string into lowercase
3. upper(): Converts all lowercase characters in a string into uppercase
4. title(): Convert string to title case.
5. capitalize(): Convert the first character of a string to uppercase

Examples:

my_string = "Hello, World!"


print(len(my_string)) # Prints the length of the string

# Python3 program to show the


# working of upper() function
text = 'WelCome To Ru'

# upper() function to convert


# string to upper case
print("\nConverted String:")
print([Link]())
# lower() function to convert
# string to lower case
print("\nConverted String:")
print([Link]())

# converts the first character to


# upper case and rest to lower case
print("\nConverted String:")
print([Link]())

#swaps the case of all characters in the string


# upper case character to lowercase and viceversa
print("\nConverted String:")
print([Link]())

# convert the first character of a string to uppercase


print("\nConverted String:")
print([Link]())

# original string never changes


print("\nOriginal String")
print(text)

Output:
13
Converted String:
WELCOME TO RU

Converted String:
welcome to ru

Converted String:
Welcome To Ru

Converted String:
wELcOME tO rU

Converted String:
Welcome to ru

Original String
WelCome To Ru

More important methods of strings:

1. replace() method: Replaces all occurrences of the substring old with new in the string.
Optionally, you can specify a maximum number of replacements with the count parameter.

Syntax: replace(old, new, count):

Example:
sentence = "This is a sample sentence."
new_sentence = [Link]("sample", "modified")
print("New sentence:", new_sentence)
# Output:
New sentence: This is a modified sentence.

2. split() method: Splits the string into a list of substrings based on the specified separator
sep. If sep is not provided, it splits on whitespace by default.

Syntax: split([sep):

Example:

sentence = "This is a sample sentence."


words = [Link]()
print("Words:", words)

# Output:
['This', 'is', 'a', 'sample', 'sentence.']

3. format() method: The format() method in Python is used to format strings. It allows you
to create formatted strings by inserting values into a placeholder within a string. The
general syntax for using format() is:
Syntax: formatted_string = "Some text with {} and {}".format(value1, value2)
1. {} as a placeholder: Curly braces {} are used as placeholders in the string, where you
want to insert values.
2. .format() method: This is called on a string and takes the values to be inserted into
the placeholders.
3. Values: These are the values you want to insert into the placeholders.
● The values provided to the format() method will replace the corresponding
placeholders in the string.
● You can also specify formatting options within the placeholders to control the
appearance of the inserted values (e.g., specifying precision for floating point
numbers).
Example:

# Basic usage
name = "Shivam"
age = 29
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

# Output:
"My name is Shivam and I am 29 years old."

# Formatting with specific precision for floating point numbers


pi_value = 3.14159265359
formatted_pi = "Pi value with 2 decimal places: {:.2f}".format(pi_value)
print(formatted_pi)

# Output:
"Pi value with 2 decimal places: 3.14"
4. isalnum() method: the isalnum() method is a string method used to check whether all
characters in a given string are either alphabetic characters (letters) or digits only. It returns
True if all characters in the string are letters or digits, and False otherwise. Spaces and
punctuation are considered as non-alphabetic characters.
Syntax: [Link] ()
Example:

pswd = "Abc12345"

if(len(pswd) >= 8 and len(pswd) <= 15):


if [Link]():
print("Good password!")
else:
print("Password should contain alpha numeric characters!")

else:
print("Password length should be in range [8-15]")

Output:
Good password!

String module:
The string module in Python provides constants and classes useful for working with strings.

The string module provides several constants, including:

1. string.ascii_letters: Concatenation of the ASCII lowercase and uppercase letters.

2. string.ascii_lowercase: String containing all ASCII lowercase letters.

3. string.ascii_uppercase: String containing all ASCII uppercase letters.

4. [Link]: String containing all ASCII digits.

5. [Link]: String containing all ASCII hexadecimal digits (0-9, a-f, A-F).

6. [Link]: String containing all ASCII octal digits (0-7).

7. [Link]: String containing all ASCII punctuation characters.

8. [Link]: String containing all printable ASCII characters (including whitespace).

Examples:

import string

print(string.ascii_letters)

# Output:

abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print([Link])

# Output:

0123456789

print([Link])

# Output:

!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~

Lists as Arrays
In Python, lists are often used as dynamic arrays due to their flexibility and ease of use. While lists in
Python are not fixed-size arrays like those in some other programming languages, they can be used
similarly to implement array-like behavior.

1. Dynamic Sizing: Lists in Python can dynamically resize themselves as needed when elements
are added or removed, making them suitable for dynamic array-like behavior.

2. Random Access: Like arrays, you can access elements in a list by their index. Lists support
constant-time access to elements, similar to arrays.

3. Homogeneous or Heterogeneous Data: Lists can contain elements of any data type,
including integers, floats, strings, or even other lists. This flexibility allows you to create
arrays with mixed data types if needed.

Creating Lists: You can create a list in Python using square brackets [] and separating elements with
commas ,

Example:

my_list = [1, 2, 3, 4, 5]

Common Operations:

1. Accessing Elements:

my_list = [1, 2, 3, 4, 5]

print(my_list[0])

# Output:

2. Slicing:

my_list = [1, 2, 3, 4, 5]

print(my_list[1:4])
# Output:

[2, 3, 4]

3. Appending Elements:

my_list = [1, 2, 3]

my_list.append(4)

print(my_list)

# Output:

[1, 2, 3, 4]

4. Inserting Elements:

my_list = [1, 2, 4]

my_list.insert(2, 3) # Insert 3 at index 2

print(my_list)

# Output:

[1, 2, 3, 4]

5. Removing Elements:

my_list = [1, 2, 3, 4]

my_list.remove(3)

print(my_list)

# Output:

[1, 2, 4]

6. Length:

my_list = [1, 2, 3, 4, 5]

length = len(my_list)

print(length)

# Output:

5
Illustrative Programs:
1. Square Root:
import math

num = int(input("Enter Number : "))


print("Square root of", num, "is", [Link](num))

2. Greatest Common Divisor (GCD):


import math

a = int(input("Enter Number a : "))


b = int(input("Enter Number b: "))

print("GCD of", a, "and", b, "is", [Link](a, b))

3. Exponentiation:
def power(base, exponent):
return base ** exponent

base = int(input("Enter base : "))

exponent = int(input("Enter exponent : "))

print(base, "raised to the power of", exponent, "is", power(base,


exponent))

4. Sum an Array of Numbers:

#array of numbers
numbers = [1, 2, 3, 4, 5]
print("Sum of", numbers, "is", sum(arr))

5. Linear Search:
In linear search, each element in the list is checked one by one until the target element is
found.

def linear_search(arr, target):


for i in range(len(arr)):
if arr[i] == target:
return i # Return the index of the target element
return -1 # Return -1 if target is not found

# Example usage:
arr = [10, 23, 45, 70, 11, 15]
target = 70
result = linear_search(arr, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

6. Binary Search:
In binary search, the list must be sorted. The algorithm repeatedly divides the list in half and
compares the middle element to the target, adjusting the search range accordingly.

def binary_search(arr, target):


left = 0
right = len(arr) - 1

while left <= right:


mid = (left + right) // 2 # Find the middle element

if arr[mid] == target:
return mid # Target found, return the index
elif arr[mid] < target:
left = mid + 1 # Search the right half
else:
right = mid - 1 # Search the left half

return -1 # Return -1 if target is not found

# Example usage:
arr = [11, 15, 23, 45, 70, 89]
target = 70
result = binary_search(arr, target)

if result != -1:
print(f"Element found at index {result}")
else:
print("Element not found")

You might also like