0% found this document useful (0 votes)
3 views22 pages

Python String

The document provides an overview of string manipulation in Python, covering string creation, indexing, slicing, immutability, and common string methods. It also discusses exception handling, including the use of try, except, else, and finally blocks, along with examples of common exceptions and their handling. Additionally, it introduces the NumPy library for numerical computations and basic array operations.

Uploaded by

s samyuktha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Python String

The document provides an overview of string manipulation in Python, covering string creation, indexing, slicing, immutability, and common string methods. It also discusses exception handling, including the use of try, except, else, and finally blocks, along with examples of common exceptions and their handling. Additionally, it introduces the NumPy library for numerical computations and basic array operations.

Uploaded by

s samyuktha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

A string is a sequence of 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.

s = "GfG"

print(s[1]) # access 2nd char

s1 = s + s[0] # update

print(s1) # print

Output
f

GfGG

In this example, s holds the value "GfG" and is defined as a string.


Creating a String
Strings can be created using either single (') or double (") quotes.
s1 = 'GfG'

s2 = "GfG"

print(s1)

print(s2)

Output

GfG

GfG

Multi-line Strings
If we need a string to span multiple lines then we can use triple quotes (''' or """).
s = """I am Learning

Python String on GeeksforGeeks"""


print(s)

s = '''I'm a

Geek'''

print(s)

Output

I am Learning

Python String on GeeksforGeeks

I'm a

Geek

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.

s = "GeeksforGeeks"

# Accesses first character: 'G'

print(s[0])

# Accesses 5th character: 's'

print(s[4])
Output

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.
Access string with Negative Indexing
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.
s = "GeeksforGeeks"

# Accesses 3rd character: 'k'

print(s[-10])

# Accesses 5th character from end: 'G'

print(s[-5])

Output

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).
s = "GeeksforGeeks"

# Retrieves characters from index 1 to 3: 'eek'

print(s[1:4])

# Retrieves characters from beginning to index 2: 'Gee'

print(s[:3])
# Retrieves characters from index 3 to the end: 'ksforGeeks'

print(s[3:])

# Reverse a string

print(s[::-1])

Output

eek

Gee

ksforGeeks

skeeGrofskeeG

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.
s = "geeksforGeeks"

# Trying to change the first character raises an error

# s[0] = 'I' # Uncommenting this line will cause a TypeError

# Instead, create a new string

s = "G" + s[1:]

print(s)

Output

GeeksforGeeks

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.
s = "GfG"

# Deletes entire string


del s
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.
Updating a String
To update a part of a string we need to create a new string since strings are immutable.
s = "hello geeks"

# Updating by creating a new string

s1 = "H" + s[1:]

# replacnig "geeks" with "GeeksforGeeks"

s2 = s.replace("geeks", "GeeksforGeeks")

print(s1)

print(s2)

Output
Hello geeks

hello GeeksforGeeks

Explanation:
 For s1, The original string s is sliced from index 1 to end of string and then concatenate
"H" to create a new string s1.
 For s2, we can created a new string s2 and used replace() method to replace 'geeks' with
'GeeksforGeeks'.
Common String Methods
Python provides a various built-in methods to manipulate strings. Below are some of the most
useful methods.
len(): The len() function returns the total number of characters in a string.
s = "GeeksforGeeks"

print(len(s))

# output: 13

Output
13

upper() and lower(): upper() method converts all characters to uppercase. lower() method
converts all characters to lowercase.
s = "Hello World"

print(s.upper()) # output: HELLO WORLD

print(s.lower()) # output: hello world

Output
HELLO WORLD

hello world

strip() and replace(): strip() removes leading and trailing whitespace from the string
and replace(old, new) replaces all occurrences of a specified substring with another.
s = " Gfg "

# Removes spaces from both ends

print(s.strip())

s = "Python is fun"

# Replaces 'fun' with 'awesome'

print(s.replace("fun", "awesome"))

Output

Gfg

Python is awesome
To learn more about string methods, please refer to Python String Methods .
Concatenating and Repeating Strings
We can concatenate strings using + operator and repeat them using * operator.
Strings can be combined by using + operator.
s1 = "Hello"

s2 = "World"

s3 = s1 + " " + s2

print(s3)

Output
Hello World

We can repeat a string multiple times using * operator.


s = "Hello "

print(s * 3)

Output

Hello Hello Hello

Formatting Strings
Python provides several ways to include variables inside strings.
Using f-strings
The simplest and most preferred way to format strings is by using f-strings.
name = "Alice"

age = 22

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

Output

Name: Alice, Age: 22

Using format()
Another way to format strings is by using format() method.

s = "My name is {} and I am {} years old.".format("Alice", 22)

print(s)

output

My name is Alice and I am 22 years old.

Using in for String Membership Testing


The in keyword checks if a particular substring is present in a string.
s = "GeeksforGeeks"

print("Geeks" in s)

print("GfG" in s)

Output
True

False
Python Exception Handling

Python Exception Handling handles errors that occur during the execution of a program.
Exception handling allows to respond to the error, instead of crashing the running program. It
enables you to catch and manage errors, making your code more robust and user-friendly. Let's
look at an example:

Handling a Simple Exception in Python

Exception handling helps in preventing crashes due to errors. Here’s a basic example
demonstrating how to catch an exception and handle it gracefully:

# Simple Exception Handling Example

n = 10

try:

res = n / 0 # This will raise a ZeroDivisionError

except ZeroDivisionError:

print("Can't be divided by zero!")

Output
Can't be divided by zero!
Explanation: In this example, dividing number by 0 raises a ZeroDivisionError. The try
block contains the code that might cause an exception and the except block handles the
exception, printing an error message instead of stopping the program.
Difference Between Exception and Error
 Error: Errors are serious issues that a program should not try to handle. They are usually
problems in the code's logic or configuration and need to be fixed by the programmer.
Examples include syntax errors and memory errors.
 Exception: Exceptions are less severe than errors and can be handled by the program. They
occur due to situations like invalid input, missing files or network issues.
Example:
# Syntax Error (Error)

print("Hello world" # Missing closing parenthesis

# ZeroDivisionError (Exception)

n = 10

res = n / 0

Explanation: A syntax error is a coding mistake that prevents the code from running. In
contrast, an exception like ZeroDivisionError can be managed during the program's execution
using exception handling.
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
 try Block: try block lets us test a block of code for errors. Python will "try" to execute the
code in this block. If an exception occurs, execution will immediately jump to the except
block.
 except Block: except block enables us to handle the error or exception. If the code inside
the try block throws an error, Python jumps to the except block and executes it. We can
handle specific exceptions or use a general except to catch all exceptions.
 else Block: else block is optional and if included, must follow all except blocks. The else
block runs only if no exceptions are raised in the try block. This is useful for code that
should execute if the try block succeeds.
 finally Block: finally block always runs, regardless of whether an exception occurred or
not. It is typically used for cleanup operations (closing files, releasing resources).
Example:
try:

n=0
res = 100 / n

except ZeroDivisionError:

print("You can't divide by zero!")

except ValueError:

print("Enter a valid number!")

else:

print("Result is", res)

finally:

print("Execution complete.")

You can't divide by zero!

Execution complete.

Explanation:

 try block asks for user input and tries to divide 100 by the input number.

 except blocks handle ZeroDivisionError and ValueError.

 else block runs if no exception occurs, displaying the result.

 finally block runs regardless of the outcome, indicating the completion of execution.

Common Exceptions in Python

Python has many built-in exceptions, each representing a specific error condition. Some common
ones include:

Exception Name Description

BaseException The base class for all built-in exceptions.

Exception The base class for all non-exit exceptions.


Exception Name Description

ArithmeticError Base class for all errors related to arithmetic operations.

Raised when a division or modulo operation is performed with zero as


ZeroDivisionError the divisor.

Raised when a numerical operation exceeds the maximum limit of a


OverflowError data type.

FloatingPointError Raised when a floating-point operation fails.

AssertionError Raised when an assert statement fails.

AttributeError Raised when an attribute reference or assignment fails.

IndexError Raised when a sequence subscript is out of range.

KeyError Raised when a dictionary key is not found.

MemoryError Raised when an operation runs out of memory.

NameError Raised when a local or global name is not found.

OSError Raised when a system-related operation (like file I/O) fails.

TypeError Raised when an operation or function is applied to an object of


Exception Name Description

inappropriate type.

Raised when a function receives an argument of the right type but


ValueError inappropriate value.

ImportError Raised when an import statement has issues.

ModuleNotFoundErro
Raised when a module cannot be found.
r

Python Catching Exceptions

When working with exceptions in Python, we can handle errors more efficiently by specifying
the types of exceptions we expect. This can make code both safer and easier to debug.

Catching Specific Exceptions

Catching specific exceptions makes code to respond to different exception types differently.
Example:
try:

x = int("str") # This will cause ValueError

#inverse

inv = 1 / x

except ValueError:

print("Not Valid!")

except ZeroDivisionError:

print("Zero has no inverse!")

Output

Not Valid!
Explanation:
 The ValueError is caught because the string "str" cannot be converted to an integer.
 If x were 0 and conversion successful, the ZeroDivisionError would be caught when
attempting to calculate its inverse.
Catching Multiple Exceptions
We can catch multiple exceptions in a single block if we need to handle them in the same way
or we can separate them if different types of exceptions require different handling.
Example:
a = ["10", "twenty", 30] # Mixed list of integers and strings

try:

total = int(a[0]) + int(a[1]) # 'twenty' cannot be converted to int

except (ValueError, TypeError) as e:

print("Error", e)

except IndexError:

print("Index out of range.")

Output

Error invalid literal for int() with base 10: 'twenty'


Explanation:
 The ValueError is caught when trying to convert "twenty" to an integer.
 TypeError might occur if the operation was incorrectly applied to non-integer types, but it's
not triggered in this specific setup.
 IndexError would be caught if an index outside the range of the list was accessed, but in
this scenario, it's under control.
Catch-All Handlers and Their Risks
Here's a simple calculation that may fail due to various reasons.
Example:
try:

# Simulate risky calculation: incorrect type operation

res = "100" / 20

except ArithmeticError:

print("Arithmetic problem.")

except:

print("Something went wrong!")


Output

Something went wrong!

Explanation:

 An ArithmeticError (more specific like ZeroDivisionError) might be caught if this were a


number-to-number division error. However, TypeError is actually triggered here due to
attempting to divide a string by a number.

 catch-all except: is used to catch the TypeError, demonstrating the risk that the
programmer might not realize the actual cause of the error (type mismatch) without more
detailed error logging.

Raise an Exception

We raise an exception in Python using the raise keyword followed by an instance of the
exception class that we want to trigger. We can choose from built-in exceptions or define our
own custom exceptions by inheriting from Python's built-in Exception class.

Basic Syntax:

raise ExceptionType("Error message")

Example:

def set(age):

if age < 0:

raise ValueError("Age cannot be negative.")

print(f"Age set to {age}")

try:

set(-5)

except ValueError as e:

print(e)

Output

Age cannot be negative.

Explanation:
 The function set checks if the age is negative. If so, it raises a ValueError with a message
explaining the issue.

 This ensures that the age attribute cannot be set to an invalid state, thus maintaining the
integrity of the data.

Advantages of Exception Handling:

 Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.

 Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.

 Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.

 Easier debugging: When an exception is raised, the Python interpreter prints a traceback
that shows the exact location where the exception occurred, making it easier to debug
your code.

Disadvantages of Exception Handling:

 Performance overhead: Exception handling can be slower than using conditional


statements to check for errors, as the interpreter has to perform additional work to catch
and handle the exception.

 Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex error
handling logic.

 Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it's important to handle
exceptions carefully and avoid exposing too much information about your program.

NumPy is a powerful Python library used for numerical computations, especially for working
with arrays and matrices. It provides efficient data structures and functions optimized for
mathematical operations.

Python

import numpy as np
# Creating NumPy arrays

arr1 = np.array([1, 2, 3, 4, 5])

arr2 = np.array([[1, 2, 3], [4, 5, 6]])

# Basic array operations

print("Array addition:", arr1 + 10)

print("Array multiplication:", arr1 * 2)

print("Array sum:", np.sum(arr1))

print("Array mean:", np.mean(arr1))

# Matrix operations

matrix1 = np.array([[1, 2], [3, 4]])

matrix2 = np.array([[5, 6], [7, 8]])

print("Matrix addition:\n", matrix1 + matrix2)

print("Matrix multiplication:\n", np.dot(matrix1, matrix2))

print("Matrix transpose:\n", matrix1.T)

print("Matrix inverse:\n", np.linalg.inv(matrix1))

 The Data pointer indicates the memory address of the first byte in the
array.
 The Data type or dtype pointer describes the kind of elements that are
contained within the array.
 The shape indicates the shape of the array.
 The strides are the number of bytes that should be skipped in memory to
go to the next element.
Operations on Numpy Array
Arithmetic Operations:
# Python code to perform arithmetic

# operations on NumPy array


import numpy as np

# Initializing the array

arr1 = np.arange(4, dtype = np.float_).reshape(2, 2)

print('First array:')

print(arr1)

print('\nSecond array:')

arr2 = np.array([12, 12])

print(arr2)

print('\nAdding the two arrays:')

print(np.add(arr1, arr2))

print('\nSubtracting the two arrays:')

print(np.subtract(arr1, arr2))

print('\nMultiplying the two arrays:')

print(np.multiply(arr1, arr2))

print('\nDividing the two arrays:')

print(np.divide(arr1, arr2))

Output:
First array:
[[ 0. 1.]
[ 2. 3.]]
Second array:
[12 12]

Adding the two arrays:


[[ 12. 13.]
[ 14. 15.]]

Subtracting the two arrays:


[[-12. -11.]
[-10. -9.]]

Multiplying the two arrays:


[[ 0. 12.]
[ 24. 36.]]

Dividing the two arrays:


[[ 0. 0.08333333]
[ 0.16666667 0.25 ]]
numpy.reciprocal() This function returns the reciprocal of argument,
element-wise. For elements with absolute values larger than 1, the result is
always 0 and for integer 0, overflow warning is issued. Example:
# Python code to perform reciprocal operation

# on NumPy array

import numpy as np

arr = np.array([25, 1.33, 1, 1, 100])

print('Our array is:')

print(arr)
print('\nAfter applying reciprocal function:')

print(np.reciprocal(arr))

arr2 = np.array([25], dtype = int)

print('\nThe second array is:')

print(arr2)

print('\nAfter applying reciprocal function:')

print(np.reciprocal(arr2))

Output
Our array is:
[ 25. 1.33 1. 1. 100. ]

After applying reciprocal function:


[ 0.04 0.7518797 1. 1. 0.01 ]

The second array is:


[25]

After applying reciprocal function:


[0]
numpy.power() This function treats elements in the first input array as the
base and returns it raised to the power of the corresponding element in the
second input array.
# Python code to perform power operation

# on NumPy array

import numpy as np

arr = np.array([5, 10, 15])


print('First array is:')

print(arr)

print('\nApplying power function:')

print(np.power(arr, 2))

print('\nSecond array is:')

arr1 = np.array([1, 2, 3])

print(arr1)

print('\nApplying power function again:')

print(np.power(arr, arr1))

Output:
First array is:
[ 5 10 15]

Applying power function:


[ 25 100 225]

Second array is:


[1 2 3]

Applying power function again:


[ 5 100 3375]
numpy.mod() This function returns the remainder of division of the
corresponding elements in the input array. The function numpy.remainder()
also produces the same result.
# Python code to perform mod function

# on NumPy array

import numpy as np
arr = np.array([5, 15, 20])

arr1 = np.array([2, 5, 9])

print('First array:')

print(arr)

print('\nSecond array:')

print(arr1)

print('\nApplying mod() function:')

print(np.mod(arr, arr1))

print('\nApplying remainder() function:')

print(np.remainder(arr, arr1))

Output:
First array:
[ 5 15 20]

Second array:
[2 5 9]

Applying mod() function:


[1 0 2]

Applying remainder() function:


[1 0 2]

You might also like