Python String
Python String
This
includes letters, numbers, and symbols. Python has no character data type so single character is
a string of length 1.
s = "GfG"
s1 = s + s[0] # update
print(s1) # print
Output
f
GfGG
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
s = '''I'm a
Geek'''
print(s)
Output
I am Learning
I'm a
Geek
s = "GeeksforGeeks"
print(s[0])
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"
print(s[-10])
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"
print(s[1:4])
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"
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"
s1 = "H" + s[1:]
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"
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 "
print(s.strip())
s = "Python is fun"
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
print(s * 3)
Output
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
Output
Using format()
Another way to format strings is by using format() method.
print(s)
output
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:
Exception handling helps in preventing crashes due to errors. Here’s a basic example
demonstrating how to catch an exception and handle it gracefully:
n = 10
try:
except ZeroDivisionError:
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)
# 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:
except ValueError:
else:
finally:
print("Execution complete.")
Execution complete.
Explanation:
try block asks for user input and tries to divide 100 by the input number.
finally block runs regardless of the outcome, indicating the completion of execution.
Python has many built-in exceptions, each representing a specific error condition. Some common
ones include:
inappropriate type.
ModuleNotFoundErro
Raised when a module cannot be found.
r
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 makes code to respond to different exception types differently.
Example:
try:
#inverse
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
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:
print("Error", e)
except IndexError:
Output
res = "100" / 20
except ArithmeticError:
print("Arithmetic problem.")
except:
Explanation:
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:
Example:
def set(age):
if age < 0:
try:
set(-5)
except ValueError as e:
print(e)
Output
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.
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.
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
# Matrix operations
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
print('First array:')
print(arr1)
print('\nSecond array:')
print(arr2)
print(np.add(arr1, arr2))
print(np.subtract(arr1, arr2))
print(np.multiply(arr1, arr2))
print(np.divide(arr1, arr2))
Output:
First array:
[[ 0. 1.]
[ 2. 3.]]
Second array:
[12 12]
# on NumPy array
import numpy as np
print(arr)
print('\nAfter applying reciprocal function:')
print(np.reciprocal(arr))
print(arr2)
print(np.reciprocal(arr2))
Output
Our array is:
[ 25. 1.33 1. 1. 100. ]
# on NumPy array
import numpy as np
print(arr)
print(np.power(arr, 2))
print(arr1)
print(np.power(arr, arr1))
Output:
First array is:
[ 5 10 15]
# on NumPy array
import numpy as np
arr = np.array([5, 15, 20])
print('First array:')
print(arr)
print('\nSecond array:')
print(arr1)
print(np.mod(arr, arr1))
print(np.remainder(arr, arr1))
Output:
First array:
[ 5 15 20]
Second array:
[2 5 9]