JUPYTER NOTEBOOK
https://jupyter.org/try-jupyter/notebooks/?path=Untitled.ipynb
TRY THESE CODES - PLOTTING, AND ALSO TUPLES AND LISTS
Matplotlib
Matplotlib is a Python library used for data visualization. It allows you to create a wide range of graphs,
charts, and plots to represent data visually. It is widely used in data science, machine learning, and scientific
computing.
● Import Matplotlib in Python: import matplotlib.pyplot as plt
1. Basic Line Plot
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 50]
plt.plot(x, y, marker='o', linestyle='-', color='b', label="Growth") #markers: https://matplotlib.org/stable/api/markers_api.html
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("Simple Line Plot")
plt.legend() # Shows the label
plt.grid(True) # Adds a grid
plt.show()
Explanation:
● marker='o' → Marks each data point.
● linestyle='-' → Solid line style.
● color='b' → Blue color.
● plt.legend() → Adds a legend.
● plt.grid(True) → Displays grid.
2. Bar Chart
x = ["A", "B", "C", "D"]
y = [10, 20, 15, 25]
plt.bar(x, y, color=['red', 'blue', 'green', 'purple'])
plt.xlabel("Categories")
plt.ylabel("Values")
plt.title("Bar Chart Example")
plt.show()
3. Scatter Plot
x = [10, 20, 30, 40, 50]
y = [5, 15, 25, 35, 45]
plt.scatter(x, y, color='r', marker='x', s=100)
plt.xlabel("X Values")
plt.ylabel("Y Values")
plt.title("Scatter Plot Example")
plt.show()
Explanation:
● marker='x' → Marks each point with "x".
● s=100 → Size of points.
4. Histogram
import numpy as np
data = np.random.randn(1000) # Generate random data
plt.hist(data, bins=30, color='blue', edgecolor='black', alpha=0.7)
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.title("Histogram Example")
plt.show()
Explanation:
● bins=30 → Divides data into 30 intervals.
● alpha=0.7 → Sets transparency.
5. Pie Chart
labels = ["Apple", "Banana", "Cherry", "Dates"]
sizes = [20, 30, 25, 25]
colors = ["red", "yellow", "pink", "brown"]
plt.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
plt.title("Pie Chart Example")
plt.show()
Explanation:
● autopct='%1.1f%%' → Shows percentage.
● startangle=90 → Starts pie from 90 degrees.
Introduction to Lists
A list in Python is a mutable (modifiable) collection of elements that can store values of different data types.
Lists are ordered and indexed, meaning elements can be accessed by their position.
Creating a List
Lists are created using square brackets [ ].
# Creating lists with different data types
numbers = [10, 20, 30, 40, 50]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
print(numbers) # Output: [10, 20, 30, 40, 50]
print(fruits) # Output: ['apple', 'banana', 'cherry']
print(mixed) # Output: [1, 'hello', 3.14, True]
Accessing Elements in a List
You can access elements in a list using indexing (0-based) or negative indexing (-1 for the last element).
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Modifying List Elements (Since Lists are Mutable)
fruits[1] = "mango"
print(fruits) # Output: ['apple', 'mango', 'cherry']
List Operations
1. Append (Add an Element to the End)
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. Insert (Add an Element at a Specific Position)
numbers.insert(1, 100)
print(numbers) # Output: [1, 100, 2, 3, 4]
3. Extend (Merge Two Lists)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
4. Sorting a List
numbers = [5, 3, 8, 1, 9]
numbers.sort()
print(numbers) # Output: [1, 3, 5, 8, 9]
Sort in Descending Order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 8, 5, 3, 1]
5. Searching for an Element in a List
numbers = [10, 20, 30, 40, 50]
print(30 in numbers) # Output: True
Other Useful List Methods
Removing Elements
numbers = [1, 2, 3, 4, 5]
numbers.remove(3) # Removes the first occurrence of 3
print(numbers) # Output: [1, 2, 4, 5]
Popping an Element
numbers.pop() # Removes the last element
print(numbers) # Output: [1, 2, 4]
numbers.pop(1) # Removes element at index 1
print(numbers) # Output: [1, 4]
Finding Index of an Element
numbers = [10, 20, 30, 40, 50]
print(numbers.index(30)) # Output: 2
Counting Occurrences of an Element
numbers = [1, 2, 3, 1, 1, 4]
print(numbers.count(1)) # Output: 3
Reversing a List
numbers.reverse()
print(numbers) # Output: [4, 1, 1, 3, 2, 1]
Introduction to Tuples
A tuple is an immutable (unchangeable) collection of ordered elements. Tuples are faster and use less memory
compared to lists.
Creating a Tuple
Tuples are created using parentheses ( ).
fruits = ("apple", "banana", "cherry")
print(fruits) # Output: ('apple', 'banana', 'cherry')
Creating a Tuple with One Element → Add a comma (,)
single_element_tuple = ("hello",)
print(type(single_element_tuple)) # Output: <class 'tuple'>
Accessing Tuple Elements
Works like lists, using indexing.
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Immutable Nature of Tuples
Tuples cannot be modified after creation.
❌
fruits = ("apple", "banana", "cherry")
# fruits[1] = "mango" # This will raise an error
Deleting a Tuple
fruits = ("apple", "banana", "cherry")
❌
del fruits
# print(fruits) # This will cause an error
Converting Between Lists and Tuples
Convert List to Tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4)
Convert Tuple to List
my_tuple = (10, 20, 30, 40)
my_list = list(my_tuple)
print(my_list) # Output: [10, 20, 30, 40]
Key Differences Between Lists and Tuples
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax Square brackets [ ] Parentheses ( )
Performance Slower Faster
Memory Usage Uses more memory Uses less memory
When to Use When modifications are needed When data should remain constant
Introduction to Python
Python is a high-level, interpreted, general-purpose programming language that emphasizes code
readability and simplicity. It was created by Guido van Rossum and first released in 1991. Python is widely used in various
fields, including web development, data science, artificial intelligence, machine learning, automation, and
scientific computing.
Python is known for its clean and readable syntax, making it an excellent choice for both beginners and
experienced programmers.
Features of Python
1. Easy to Learn and Use
● Python has a simple and intuitive syntax that resembles English, making it easy to read and write.
2. Interpreted Language
● Python does not require compilation; it is executed line-by-line by the Python interpreter.
● This makes debugging easier compared to compiled languages like C or Java.
3. Cross-Platform Compatibility
● Python is platform-independent, meaning a Python program can run on Windows, macOS, Linux, and
other operating systems without modification.
4. Open-Source and Free
● Python is open-source, meaning its source code is freely available to everyone.
5. Large Standard Library
● Python comes with a vast collection of built-in modules and libraries for handling tasks like:
○ Mathematics (math, random)
○ Data manipulation (pandas, NumPy)
○ Web development (Flask, Django)
○ Machine learning (TensorFlow, scikit-learn)
○ Data visualization (Matplotlib, Seaborn)
6. Object-Oriented and Procedural Programming
● Python supports both object-oriented programming (OOP) and procedural programming styles.
● OOP is a programming paradigm that uses objects and classes to structure and organize code efficiently. Python
is an object-oriented language, meaning it supports OOP principles.
○ Class and Object
■ Class → A blueprint or template for creating objects.
■ Object → An instance of a class with real values.
○ Encapsulation (Data Hiding)
■ The process of wrapping up data members and member functions under a single
unit. Ex - A bag may contain different stuff like pen, pencil, notebook etc within it.
■ Encapsulation restricts direct access to an object's private variables, protecting data from
accidental modification.
○ Inheritance (Code Reusability)
■ The process of inheriting functions and other attributes from a parent class to a child
class. This increases reusability. Ex - A person inherits his/her family fortune.
■ Inheritance allows a class to inherit attributes and methods from another class, reducing code
repetition.
○ Parent (Base) Class → The original class.
○ Child (Derived) Class → Inherits from the parent class.
○ Polymorphism (Many Forms)
■ It describes the ability of something to have or to be represented in more than one
form. Ex - You are a daughter/son, sibling, friend, etc. to different individuals.
■ Polymorphism allows different classes to have the same method name but with different
implementations.
○ Abstraction (Hiding Implementation Details)
■ The act of representing the essential features without including the background
details. Ex - you know how to use a phone but you might not know all the details of
how a phone works.
■ Abstraction hides complex details and only shows the necessary functionalities. It is
implemented using abstract classes
7. Extensibility and Integration
● Python can integrate with other languages like C, C++, Java, and .NET for performance improvements.
8. Dynamically Typed Language
● You don’t need to declare variable types explicitly; Python automatically determines them.
9. Memory Management
● Python has automatic memory management with garbage collection, reducing memory leaks and improving
performance.
10. Scalability and Portability
● Python is scalable and suitable for both small scripts and large-scale enterprise applications.
● It is used by companies like Google, Netflix, Instagram, and NASA for production-level applications.
NumPy
NumPy (Numerical Python) is a powerful library for numerical computing in Python. It provides support for
multidimensional arrays, mathematical operations, and linear algebra, making it essential for data science, machine
learning, and scientific computing.
● Importing NumPy in Python: import numpy as np
Creating NumPy Arrays
NumPy’s main object is the ndarray (N-dimensional array), which is faster and more efficient than Python lists.
1. Creating an Array
import numpy as np
arr = np.array([1, 2, 3, 4, 5]) #providing a list
print(arr)
# Output: [1 2 3 4 5]
2. Creating Multi-dimensional Arrays
arr_2d = np.array([[1, 2, 3], [4, 5, 6]])
print(arr_2d)
# Output:
# [[1 2 3]
# [4 5 6]]
3. Checking Array Shape and Size
print(arr_2d.shape) # Output: (2, 3) → 2 rows, 3 columns
print(arr_2d.size) # Output: 6 (total elements)
Basic Useful NumPy Functions
1. Generating Arrays
● np.zeros((3, 3)) # 3x3 matrix of zeros
● np.ones((2, 2)) # 2x2 matrix of ones
● np.full((2, 3), 7) # 2x3 matrix filled with 7
● np.arange(1, 10, 2) # [1, 3, 5, 7, 9] Note that this is simply a function to generate numbers, simple to the range function
● np.linspace(0, 5, 10) # 10 values between 0 and 5
2. Array Operations
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print(arr1 + arr2) # Output: [5 7 9]
print(arr1 * arr2) # Output: [4 10 18]
print(arr1 / 2) # Output: [0.5 1.0 1.5]
print(np.sqrt(arr1)) # Square root
3. Statistical Functions
arr = np.array([10, 20, 30, 40])
print(np.mean(arr)) # Output: 25.0 (average)
print(np.median(arr)) # Output: 25.0
print(np.min(arr)) # Output: 10
print(np.max(arr)) # Output: 40
print(np.sum(arr)) # Output: 100
print(np.std(arr)) # Standard deviation
Pandas
Pandas is a powerful library in Python used for data manipulation, analysis, and visualization. It provides
DataFrames and Series, which are highly optimized structures for handling tabular and structured data (like
spreadsheets and SQL tables).
● Import Pandas in Python: import pandas as pd
1. Creating Data Structures in Pandas
Creating a DataFrame (2D Data) {just for your knowledge, not important}
A DataFrame is a table-like structure with rows and columns (like an Excel sheet).
data = {
"Name": ["Alice", "Bob", "Charlie"],
"Age": [25, 30, 35],
"City": ["New York", "Los Angeles", "Chicago"]
}
df = pd.DataFrame(data)
print(df)
Output:
Name Age City
0 Alice 25 New York
1 Bob 30 Los Angeles
2 Charlie 35 Chicago
2. Useful Pandas Functions
2.1 Reading and Writing Files
df.to_csv("data.csv", index=False) # Save as CSV
df = pd.read_csv("data.csv") # Load from CSV
df.to_excel("data.xlsx", index=False) # Save as Excel
df = pd.read_excel("data.xlsx") # Load from Excel
2.2 Summary and Descriptive Statistics
print(df.head()) # First 5 rows
print(df.tail()) # Last 5 rows
print(df.info()) # Summary of dataset
print(df.describe()) # Statistical summary
Introduction to Lists
A list in Python is a mutable (modifiable) collection of elements that can store values of different data types.
Lists are ordered and indexed, meaning elements can be accessed by their position.
Creating a List
Lists are created using square brackets [ ].
# Creating lists with different data types
numbers = [10, 20, 30, 40, 50]
fruits = ["apple", "banana", "cherry"]
mixed = [1, "hello", 3.14, True]
print(numbers) # Output: [10, 20, 30, 40, 50]
print(fruits) # Output: ['apple', 'banana', 'cherry']
print(mixed) # Output: [1, 'hello', 3.14, True]
Accessing Elements in a List
You can access elements in a list using indexing (0-based) or negative indexing (-1 for the last element).
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Modifying List Elements (Since Lists are Mutable)
fruits[1] = "mango"
print(fruits) # Output: ['apple', 'mango', 'cherry']
List Operations
1. Append (Add an Element to the End)
numbers = [1, 2, 3]
numbers.append(4)
print(numbers) # Output: [1, 2, 3, 4]
2. Insert (Add an Element at a Specific Position)
numbers.insert(1, 100)
print(numbers) # Output: [1, 100, 2, 3, 4]
3. Extend (Merge Two Lists)
list1 = [1, 2, 3]
list2 = [4, 5, 6]
list1.extend(list2)
print(list1) # Output: [1, 2, 3, 4, 5, 6]
4. Sorting a List
numbers = [5, 3, 8, 1, 9]
numbers.sort()
print(numbers) # Output: [1, 3, 5, 8, 9]
Sort in Descending Order
numbers.sort(reverse=True)
print(numbers) # Output: [9, 8, 5, 3, 1]
5. Searching for an Element in a List
numbers = [10, 20, 30, 40, 50]
print(30 in numbers) # Output: True
Other Useful List Methods
Removing Elements
numbers = [1, 2, 3, 4, 5]
numbers.remove(3) # Removes the first occurrence of 3
print(numbers) # Output: [1, 2, 4, 5]
Popping an Element
numbers.pop() # Removes the last element
print(numbers) # Output: [1, 2, 4]
numbers.pop(1) # Removes element at index 1
print(numbers) # Output: [1, 4]
Finding Index of an Element
numbers = [10, 20, 30, 40, 50]
print(numbers.index(30)) # Output: 2
Counting Occurrences of an Element
numbers = [1, 2, 3, 1, 1, 4]
print(numbers.count(1)) # Output: 3
Reversing a List
numbers.reverse()
print(numbers) # Output: [4, 1, 1, 3, 2, 1]
Introduction to Tuples
A tuple is an immutable (unchangeable) collection of ordered elements. Tuples are faster and use less memory
compared to lists.
Creating a Tuple
Tuples are created using parentheses ( ).
fruits = ("apple", "banana", "cherry")
print(fruits) # Output: ('apple', 'banana', 'cherry')
Creating a Tuple with One Element → Add a comma (,)
single_element_tuple = ("hello",)
print(type(single_element_tuple)) # Output: <class 'tuple'>
Accessing Tuple Elements
Works like lists, using indexing.
fruits = ("apple", "banana", "cherry")
print(fruits[0]) # Output: apple
print(fruits[-1]) # Output: cherry
Immutable Nature of Tuples
Tuples cannot be modified after creation.
❌
fruits = ("apple", "banana", "cherry")
# fruits[1] = "mango" # This will raise an error
Deleting a Tuple
fruits = ("apple", "banana", "cherry")
❌
del fruits
# print(fruits) # This will cause an error
Converting Between Lists and Tuples
Convert List to Tuple
my_list = [1, 2, 3, 4]
my_tuple = tuple(my_list)
print(my_tuple) # Output: (1, 2, 3, 4)
Convert Tuple to List
my_tuple = (10, 20, 30, 40)
my_list = list(my_tuple)
print(my_list) # Output: [10, 20, 30, 40]
Key Differences Between Lists and Tuples
Feature List Tuple
Mutability Mutable (can be changed) Immutable (cannot be changed)
Syntax Square brackets [ ] Parentheses ( )
Performance Slower Faster
Memory Usage Uses more memory Uses less memory
When to Use When modifications are needed When data should remain constant
Conclusion
● Lists are mutable, ordered collections suitable for dynamic data.
● Tuples are immutable, ordered collections used for fixed data.
● Lists are commonly used when modifications are required, whereas tuples are used when data integrity and
performance are important.
SOME IMPORTANT CODES TO GLANCE THROUGH:
1. NumPy: Compute Mean, Standard Deviation, and Median from a List
NumPy is a powerful Python library used for numerical computing. Here, we demonstrate how to compute the mean,
standard deviation, and median of a given list using NumPy.
Code:
import numpy as np
# Define a list of numbers
data = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
# Compute statistical values
mean_value = np.mean(data) # Mean
std_deviation = np.std(data) # Standard deviation
median_value = np.median(data) # Median
# Print results
print("Mean:", mean_value)
print("Standard Deviation:", std_deviation)
print("Median:", median_value)
Explanation:
● np.mean(data): Computes the mean (average) of the numbers in the list.
● np.std(data): Computes the standard deviation, a measure of data spread.
● np.median(data): Computes the median, the middle value in a sorted list.
2. Manipulating a DataFrame Using Pandas
Pandas is a popular data analysis library. Here, we demonstrate loading a CSV file and various functions to print specific
portions of a dataset.
Code:
import pandas as pd
# Load the CSV file (Make sure the file exists in the same directory)
df = pd.read_csv("data.csv") # Replace "data.csv" with the actual filename
# Print the entire DataFrame
print("Entire DataFrame:")
print(df)
# Print the first 5 rows
print("\nFirst 5 rows:")
print(df.head())
# Print the last 5 rows
print("\nLast 5 rows:")
print(df.tail())
# Print a custom range (e.g., rows 3 to 7)
print("\nRows from index 3 to 7:")
print(df.iloc[3:8])
# Print a specific column
print("\nValues from column 'Name':")
print(df["Name"]) # Replace "Name" with an actual column in your CSV
Explanation:
● pd.read_csv("data.csv"): Loads a CSV file into a DataFrame.
● df.head(): Displays the first 5 rows of the DataFrame.
● df.tail(): Displays the last 5 rows.
● df.iloc[3:8]: Retrieves a custom range of rows.
● df["Name"]: Prints a specific column.
3. Solving Linear Equations Using SciPy
SciPy provides functions for scientific computing, including solving systems of linear equations of the form:
Ax = B, where A is the coefficient matrix and B is the constant matrix.
Code:
import numpy as np
from scipy.linalg import solve
# Define the coefficient matrix (A)
A = np.array([[3, 2], [1, 4]])
# Define the constant matrix (B)
B = np.array([5, 6])
# Solve the system of equations
solution = solve(A, B)
# Print the solution
print("Solution for x and y:", solution)
Explanation:
The system of equations:
3x + 2y = 5
1x + 4y = 6
● We represent this as A (coefficients) and B (constants).
● solve(A, B): Finds the values of x and y.
4. Plotting Lists as Points Using Matplotlib
Matplotlib allows us to visualize data. Here, we plot a list of values using various colors, labels, titles, grid options, and
different marker styles.
Code:
import matplotlib.pyplot as plt
# Define data points
x_values = [1, 2, 3, 4, 5]
y_values = [10, 15, 7, 12, 9]
# Create a scatter plot with different marker styles and colors
plt.scatter(x_values, y_values, color='red', marker='o', label='Data Points')
# Add labels and title
plt.xlabel("X-axis Label")
plt.ylabel("Y-axis Label")
plt.title("Scatter Plot Example")
# Enable grid
plt.grid(True)
# Show legend
plt.legend()
# Display the plot
plt.show()
Explanation:
● plt.scatter(x, y, color='red', marker='o'): Plots the points with red circles.
● plt.xlabel(), plt.ylabel(): Adds axis labels.
● plt.title(): Sets the title of the graph.
● plt.grid(True): Enables the grid for better readability.
● plt.legend(): Displays labels for the plotted data.
Strings in Python
1. Introduction to Strings
A string in Python is a sequence of characters enclosed in single ('), double ("), or triple quotes (''' or """). Strings are
immutable, meaning their values cannot be changed once assigned.
str1 = 'Hello' # Single quotes
str2 = "World" # Double quotes
str3 = '''Python is fun!''' # Triple quotes (for multi-line strings)
2. Creating Strings
Strings can be created using assignment or by using the str() constructor.
str1 = "Python"
str2 = str(1234) # Converts an integer to a string
print(str2) # Output: '1234'
3. Traversing a String
We can iterate through a string using a for loop.
s = "Python"
for c in s:
print(c)
Output:
P
y
t
h
o
n
4. Multi-line Strings
Triple quotes (''' or """) allow multi-line string declarations.
multi_line_str = """This is
a multi-line
string in Python."""
print(multi_line_str)
5. Concatenation of Strings
Strings can be combined using the + operator.
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3) # Output: Hello World
6. Escape Sequences
Escape sequences allow the use of special characters in strings.
Escape Sequence Description
\n New Line
\t Tab Space
\' Single Quote
\" Double Quote
\\ Backslash
print("Hello\nWorld") # Output: Hello (new line) World
print("Python\tProgramming") # Output: Python (tab) Programming
7. String Operators
Operator Example Output
+ "Hello" + "World" "HelloWorld"
* "Hello" * 3 "HelloHelloHello"
[] "Python"[0] "P"
[:] "Python"[1:4] "yth"
in "P" in "Python" True
not in "X" not in "Python" True
s = "Python"
print(s[1:4]) # Output: yth
print("P" in s) # Output: True
8. String Built-in Functions
Python provides several built-in string functions.
8.1 len() – Get String Length
s = "Hello"
print(len(s)) # Output: 5
8.2 upper() – Convert to Uppercase
s = "hello"
print(s.upper()) # Output: HELLO
8.3 lower() – Convert to Lowercase
s = "HELLO"
print(s.lower()) # Output: hello
8.4 startswith(value) – Check if String Starts With a Specific Value
s = "Hello, World!"
print(s.startswith("Hello")) # Output: True
print(s.startswith("World")) # Output: False
8.5 endswith(value) – Check if String Ends With a Specific Value
s = "Hello, World!"
print(s.endswith("World!")) # Output: True
8.6 find(value) – Find First Occurrence of a Substring
s = "Hello, World!"
print(s.find("World")) # Output: 7
print(s.find("Python")) # Output: -1 (not found)
8.7 islower() – Check if String is in Lowercase
s1 = "hello"
s2 = "Hello"
print(s1.islower()) # Output: True
print(s2.islower()) # Output: False
8.8 replace(oldvalue, newvalue) – Replace Substring
s = "I love Python"
print(s.replace("Python", "Java")) # Output: I love Java
8.9 count(value) – Count Occurrences of a Substring
s = "banana"
print(s.count("a")) # Output: 3
8.10 isalpha() – Check if String Contains Only Letters
s1 = "Hello"
s2 = "Hello123"
print(s1.isalpha()) # Output: True
print(s2.isalpha()) # Output: False
8.11 isdigit() – Check if String Contains Only Digits
s1 = "12345"
s2 = "123abc"
print(s1.isdigit()) # Output: True
print(s2.isdigit()) # Output: False
8.12 isalnum() – Check if String is Alphanumeric
s1 = "Hello123"
s2 = "Hello 123"
print(s1.isalnum()) # Output: True
print(s2.isalnum()) # Output: False (contains space)
8.13 join(iterable) – Join Elements of a List into a String
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence) # Output: Python is awesome
9. String Slicing ([start:end:step])
Syntax: string[start:end:step]
s = "PythonProgramming"
print(s[0:6]) # Output: Python (characters from index 0 to 5)
print(s[::2]) # Output: PtoPormig (every second character)
print(s[::-1]) # Output: gnimmargorPnohtyP (reverse string)
Conclusion
● Strings are immutable sequences of characters.
● You can traverse, slice, and manipulate strings using built-in functions.
● Python provides powerful string methods like upper(), find(), replace(), join(), etc.
● Escape sequences allow special characters in strings.
● String slicing helps extract portions of a string.