Python Unit1
Python Unit1
PYTHON
UNIT-1
Anshu Sharma
ANSHU SHARMA
Introduction
• An ordered set of instruction to be executed by a computer to carry out
a specific task is called a program.
• As we all know computer understand only 0 and 1’s which is called
machine language or low language.
• This led to advent of high level programming language like Python,
C++, java, PHP which is easier for human being to understand.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
History
• Python is a programming language which was created by Guido Van
Rossum in 1991.
• It got its name from a BBC comedy show “Monty Python Flying
Circus”.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Features of Python
• Easy to learn, read and maintain
• Broad standard library
• Interactive mode
• Portability and compatibility
• Extendable
• Databases and scalable
Anshu Sharma
ANSHU SHARMA
Applications of Python
• Web Development
• Desktop Application
• Software Development
• Database Assess
• Network Programming
• Game Development
• 3D Graphics
Anshu Sharma
ANSHU SHARMA
Python Installation
For Windows:
Step 1: Visit the official Python website at [Link]/downloads/
Step 2: Click on the “Download Python “ button
Download the Python installer that matches your system requirements.
• Step 3: Run Executable Installer
On the Python Releases for Windows page, select the link for the latest
Python 3.x.x release
Step 4: Add Python to the path
Step 5: Verify (Go to the command prompt, type python –version)
Anshu Sharma
ANSHU SHARMA
Step 1: [Link]
Anshu Sharma
ANSHU SHARMA
Step 2:
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
IDLE in Python
• IDLE stands for Integrated Development and Learning Environment.
It is the default editor and interpreter provided with Python.
Uses of IDLE
• Helps to write Python programs
• Allows users to run and test code easily
• Provides an interactive shell for quick execution of commands
Main Features
• Python Shell: Executes commands instantly
• Editor Window: Used to write and save complete programs
Anshu Sharma
ANSHU SHARMA
Python Shell
Anshu Sharma
ANSHU SHARMA
Variables
• A variable is a named location used to store data in memory.
• It is a container that holds data that can be changed later in the
program.
In Python, we don’t actually assign a value to the variables. Instead,
Python gives the reference of the object to the variable.
• There is no need to specify the datatype of a variable
• A variable is a name given to a memory location.
Anshu Sharma
ANSHU SHARMA
• Variables are used to store values that can be used later in the program.
• For example, you can create a variable called "name" and assign it a
value like this:
Anshu Sharma
ANSHU SHARMA
• Variables in Python can hold different types of data, such as numbers,
strings, lists, or even more complex objects.
• You can change the value of a variable at any time by assigning a new
value to it. For instance:
Anshu Sharma
ANSHU SHARMA
• Python also allows you to perform operations on variables. For
example, you can add, subtract, Multiple divide variables containing
numbers. You can even combine variables of different types using
operators. For instance:
Anshu Sharma
ANSHU SHARMA
Types of Variables
• Integer → x = 10
• Float → y = 5.5
• String → name = "Python"
• Boolean → is_active = True
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Identifiers
• In Python, identifiers are the names you use to name variables, functions,
classes, or other objects. They are like labels that help you identify different
parts of your program.
Rules for Python Identifiers:
• Must start with a letter (A-Z or a-z) or an underscore (_).
Examples: name, _value
• Cannot start with a digit (0-9).
Invalid: 1name
• Can only contain letters, digits, and underscores.
Valid: my_var1
Invalid: my-var, my var
• Cannot use Python keywords (like if, else, while, def, etc.) as identifiers.
• Case-sensitive: name, Name, and NAME are different identifiers.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Constants
• Constants in Python are values that you decide should not change
while your program is running.
• How to Use Constants:
• Python doesn’t have a special way to create constants, so we use a naming
convention to show that a value is constant.
• Write constant names in ALL CAPITAL LETTERS.
• Examples:
• DAYS_IN_A_WEEK = 7
• PI = 3.14159
• GRAVITY = 9.8
Anshu Sharma
ANSHU SHARMA
Comments
• In Python, comments are lines of text in your code that are ignored by
the Python interpreter. They are used to explain what the code does,
make it more readable, or temporarily disable a piece of code.
• Types of Comments
• Single line comment:
Start the comment with # symbol
X=10 # this is single line comment
Anshu Sharma
ANSHU SHARMA
• Multi-line Comments
For longer explanations, use triple quotes (''' or """) to write comments
across multiple lines.
'‘’
This is a multi-line comment.
'''
Anshu Sharma
ANSHU SHARMA
Keywords
• In Python, keywords are special words that have a specific meaning
and purpose in the programming language. They are reserved and
cannot be used as names for variables, functions, or other identifiers.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Data types in Python refer to the different kinds of values that can be assigned
to variables. They determine the nature of the data and the operations that can
be performed on them. Python provides several built-in data types, including:
Numeric:
• Python supports different numerical data types, including integers (whole
numbers), floating-point numbers (decimal numbers), and complex numbers
(numbers with real and imaginary parts).
• Integers (int): Integers represent whole numbers without any fractional part.
For example, age = 25.
• Floating-Point Numbers (float): Floating-point numbers represent numbers
with decimal points or fractions. For example, pi = 3.14.
• Complex Numbers (complex): Complex numbers have a real and imaginary
part. They are donated by a combination of a real and imaginary number,
suffixed with j or J. For example, z = 2 + 3j.
Anshu Sharma
ANSHU SHARMA
a=5
• print(type(a))
Output: <class ‘int’>
b = 5.0
• print(type(b))
Output: <class ‘float’>
c = 2 + 4j
• print(type(c))
Output: <class ‘complex no’>
Anshu Sharma
ANSHU SHARMA
Strings (str): Strings represent sequences of characters enclosed within single or double
quotes. For example, name = "John".
s = 'Welcome to the Geeks World'
print(s)
# check data type
print(type(s))
# access string with index
print(s[1])
print(s[2])
print(s[-1])
Anshu Sharma
ANSHU SHARMA
Lists (list): Lists are ordered sequences of elements enclosed in square
brackets. Each element can be of any data type.
For example, numbers = [1, 2, 3, 4].
# Empty list
• a = []
# list with int values
• a = [1, 2, 3]
• print(a)
# list with mixed int and string
• b = ["Geeks", "For", "Geeks", 4, 5]
• print(b)
Output
• [1, 2, 3]
• ['Geeks', 'For', 'Geeks', 4, 5]
Anshu Sharma
ANSHU SHARMA
[Link]("grape")
print(fruits) ['apple', 'banana', 'orange', 'grape']
[Link]("orange")
print(fruits) ['apple', 'banana', 'grape']
Anshu Sharma
ANSHU SHARMA
• Tuples (tuple): Tuples are similar to lists but are immutable, meaning
their elements cannot be changed once defined. They are enclosed in
parentheses.
• For example, coordinates = (3, 4).
Anshu Sharma
ANSHU SHARMA
Set:
Sets (set): Sets are unordered collections of unique elements enclosed in
curly braces. They are useful for mathematical operations such as union,
intersection, and difference.
For example, fruits = {'apple', 'banana', 'orange’}.
Sets can be created by using the built-in set() function with an iterable
object or a sequence by placing the sequence inside curly braces,
separated by a ‘comma’. The type of elements in a set need not be the
same; various mixed-up data type values can also be passed to the set.
Anshu Sharma
ANSHU SHARMA
• Dictionary:
Dictionaries are key-value pairs enclosed in curly braces. Each value is
associated with a unique key, allowing for efficient lookup and
retrieval. For example, person = {'name': 'John', 'age': 25, 'city': 'New
York'}.
• Boolean:
Boolean (bool): Booleans represent truth values, either True or False.
They are used for logical operations and conditions. For example,
is_valid = True.
Anshu Sharma
ANSHU SHARMA
• Sequence Type:
Sequences represent a collection of elements and include data types like
strings, lists, and tuples. Strings are used to store textual data, while lists
and tuples are used to store ordered collections of items.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Operators in Python
• Operators in Python are symbols or special characters that are used to perform
specific operations on variables and values.
• Here are some important categories of operators in Python:
• Arithmetic operators
• Comparison operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
Anshu Sharma
ANSHU SHARMA
Arithmetic Operators:
Arithmetic operators in Python are used to perform mathematical calculations on numeric
values. The basic arithmetic operators include:
• Addition (+): Adds two operands together. For example, if we have a = 10 and b = 10,
then a + b equals 20.
• Subtraction (-): Subtracts the second operand from the first operand. If the first operand is
smaller than the second operand, the result will be negative. For example, if we have
a = 20 and b = 5, then a - b equals 15.
• Division (/): Divides the first operand by the second operand and returns the quotient. For
example, if we have a = 20 and b = 10, then a / b equals 2.0.
• Multiplication (*): Multiplies one operand by the other. For example, if we have a = 20
and b = 4, then a * b equals 80.
• Modulus (%): Returns the remainder after dividing the first operand by the second
operand. For example, if we have a = 20 and b = 10, then a % b equals 0.
Anshu Sharma
ANSHU SHARMA
• Exponentiation (**) or Power: Raises the first operand to the power of the second
operand. For example, if we have a = 2 and b = 3, then a ** b equals 8.
• Floor Division (//): Provides the floor value of the quotient obtained by dividing
the two operands. It returns the largest integer that is less than or equal to the
result. For example, if we have a = 20 and b = 3, then a // b equals 6.
Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example
+ Addition Adds two numbers. a+b 10 + 5 = 15
Subtracts second number from
- Subtraction a-b 10 - 5 = 5
first.
Anshu Sharma
ANSHU SHARMA
Comparison Operators:
Comparison operators in Python are used to compare two values and
return a Boolean value (True or False) based on the comparison.
Common comparison operators include:
• Equal to (==): Checks if two operands are equal.
• Not equal to (!=): Checks if two operands are not equal.
• Greater than (>): Checks if the left operand is greater than the right
operand.
• Less than (<): Checks if the left operand is less than the right operand.
• Greater than or equal to (>=): Checks if the left operand is greater than
or equal to the right operand.
• Less than or equal to (<=): Checks if the left operand is less than or
equal to the right operand.
Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example
• a = 13
• b = 33
• print(a > b) // False
• print(a < b) // True
• print(a == b) // False
• print(a != b) // True
• print(a >= b) // False
• print(a <= b) // True
Anshu Sharma
ANSHU SHARMA
Assignment Operators:
Assignment operators are used to assign values to variables.
They include:
• Equal to (=): Assigns the value on the right to the variable on the left.
• Com pound a ssignment opera tors ( +=, -=, *=, /=) : Perform the specified
arithmetic operation and assign the result to the variable.
Anshu Sharma
Operator Name Definition Syntax ANSHU SHARMA
Example
**= Power and Assign Raises power and assigns result. a **= b a = 2; a **= 3 → 8
Anshu Sharma
ANSHU SHARMA
a = 10
b=a
• print(b) // 10
b += a
• print(b) //20
b -= a
• print(b) //10
b *= a
• print(b) //100
Anshu Sharma
ANSHU SHARMA
Logical Operators:
Logical operators in Python are used to perform logical operations on
Boolean values. The main logical operators are:
• Logical AND (and): Returns True if both operands are True,
otherwise False.
• Logical OR (or): Returns True if at least one of the operands is True,
otherwise False.
• Logical NOT (not): Returns the opposite Boolean value of the
operand.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Bitwise Operators:
Bitwise operators perform operations on individual bits of binary numbers.
Some common bitwise operators in Python are:
• Bitwise AND (&): Performs a bitwise AND operation on the binary
representations of the operands.
• Bitwise OR (|): Performs a bitwise OR operation on the binary
representations of the operands.
• Bitwise XOR (^): Performs a bitwise exclusive OR operation on the binary
representations of the operands.
• Bitwise complement (~): Inverts the bits of the operand. Left shift (<<):
Shifts the bits of the left operand to the left by the number of positions
specified by the right operand.
• Right shift (>>): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand.
• Right shift (>>): Shifts the bits of the left operand to the right by the number
of positions specified by the right operand.
Anshu Sharma
ANSHU SHARMA
Operator Name Definition Syntax Example
& Bitwise AND Sets bit to 1 if both bits are 1. a&b 5&3→1
0 1 0
0101
1 0 0 & 0011
------
1 1 1
0001 = 1
Anshu Sharma
ANSHU SHARMA
BITWISE OR ( | )
a = 5 # 0101
A|B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)
0 1 1
0101
1 0 1 | 0011
------
1 1 1
0111 = 7
Anshu Sharma
ANSHU SHARMA
BITWISE XOR ( ^ )
a = 5 # 0101
A^B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)
0 1 1
0101
1 0 1 ^ 0011
------
1 1 0
0110 = 6
Anshu Sharma
ANSHU SHARMA
BITWISE XOR ( ^ )
a = 5 # 0101
A^B
A (Bit) B (Bit) b = 3 # 0011
(Result)
0 0 0 print(a & b)
0 1 1
0101
1 0 1 ^ 0011
------
1 1 0
0110 = 6
Anshu Sharma
ANSHU SHARMA
BITWISE NOT ( ~ )
a = 5 # 0101
A (Bit) ~A (Result) print(~a)
0 1
1010
1 0
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Precedence
Anshu Sharma
ANSHU SHARMA
Membership Operators:
Membership operators are used to test whether a value is a member of a
sequence (e.g., string, list, tuple).
They include:
• In: Returns True if the value is found in the sequence.
• Not in: Returns True if the value is not found in the sequence.
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Control Statements
If statement
An `if` statement in Python checks whether a condition is true or false. If the
condition is true, the code inside the `if` block runs. If false, the code is
skipped. It's used to make decisions in the program, executing specific
actions based on conditions
Syntax:
if condition: # Code to execute if the condition is True
Example:
x = 10
if x > 5: # Check if x is greater than 5
print("x is greater than 5")
Output:
x is greater than 5
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
if-else
If the condition is false, you can use else to specify what happens.
Example:
x=3
if x > 5:
print("x is greater than 5")
else:
print("x is less than or equal to 5")
Output:
x is less than or equal to 5
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
if-elif-else
You can check multiple conditions using elif
if [condition 1]:
print statement
elif [ condition 2]:
print statement
elif [condition 3]:
print statement
else:
statement
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Example:
temperature = 25
if temperature < 15:
print("It's cold.")
elif temperature < 30:
print("It's warm.")
else:
print("It's hot.")
Output:
It's warm.
Anshu Sharma
ANSHU SHARMA
Match-case statement
Powerful way to handle conditional logic
Used for pattern matching, similar to a switch statement
Syntax:
match variable:
case pattern1:
# Code to execute if variable matches pattern1
case pattern2:
# Code to execute if variable matches pattern2
case _:
# Default case (if no pattern matches)
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Example:
color = "red"
match color:
case "red":
print("The color is red.")
case "blue":
print("The color is blue.")
case "green":
print("The color is green.")
case _:
print("Unknown color.")
Output:
The color is red
Anshu Sharma
ANSHU SHARMA
Loops
• While Loop
A while loop in Python is used to repeatedly execute a block of code as
long as a given condition is True. Once the condition becomes False, the
loop stops.
Syntax:
while condition:
# Code to execute as long as the condition is True
Anshu Sharma
ANSHU SHARMA
Example:
count = 0
while count < 5: # Condition: keep looping while count is less than 5
print(count)
count += 1 # Increment count by 1 each time
Output:
0
1
2
3
4
Anshu Sharma
ANSHU SHARMA
• For loop
A for loop in Python is used to iterate over a sequence and execute a block of
code for each item in that sequence.
Syntax:
for item in sequence:
# Code to execute for each item in the sequence
Example:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry Anshu Sharma
ANSHU SHARMA
Example:
for i in range(5): # Loop from 0 to 4
print(i)
Output:
0
1
2
3
4
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
for i in range (1,11,1):
print(i)
Output:
1
2
3
4
5
6
7
8
9
10
Anshu Sharma
ANSHU SHARMA
• Nested Loop
A nested loop in Python means putting one loop inside another. This is useful
when we need to repeat actions within another repeated action.
Example: Printing rows and column
for row in range(1, 4): # Outer loop for rows
for column in range(1, 4): # Inner loop for columns
print(f"Row {row}, Column {column}")
Output:
Row 1, Column 1
Row 1, Column 2
Row 1, Column 3
Row 2, Column 1
Row 2, Column 2
Row 2, Column 3
Row 3, Column 1
Row 3, Column 2
Row 3, Column 3
Anshu Sharma
ANSHU SHARMA
• Break
The break statement in Python is used to exit a loop prematurely. When
break is encountered, the program immediately stops the execution of the
current loop (either for or while) and continues with the code after the loop.
Example:
for i in range(1, 6):
if i == 3: # When i is 3, exit the loop
break
print(i)
print("Loop ended.")
Output:
1
2
Loop ended.
Anshu Sharma
ANSHU SHARMA
• Continue
The continue statement in Python is used to skip the current iteration of a
loop and move to the next iteration.
• Example:
for i in range(1, 6):
if i == 3: # Skip when i is 3
continue
print(i)
• Output:
1
2
4
5
Anshu Sharma
ANSHU SHARMA
String
• In Python, a string is a sequence of characters enclosed within single quotes
('), double quotes ("), or triple quotes (''' or """). Strings are one of the most
commonly used data types and are immutable, meaning their content cannot
be changed after they are created.
• # Single-quoted strings
string1 = 'Hello, World!'
• # Double-quoted strings
string2 = "Python Strings"
• # Triple-quoted strings (used for multi-line strings or docstrings)
string3 = '''This is a
multi-line string'''
• string4 = """Another example
of a multi-line string"""
Anshu Sharma
ANSHU SHARMA
1. Single-Quoted Strings
Use single quotes (') to define a string:
Anshu Sharma
ANSHU SHARMA
2. Double-Quoted Strings
Use double quotes (") to define a string:
Anshu Sharma
ANSHU SHARMA
3. Triple-Quoted Strings
Use triple quotes (''' or """) for:
string3 = '''This is a
multi-line string'''
print(string3)
Anshu Sharma
ANSHU SHARMA
Length of String
• The length of a string in Python can be determined using the built-in
len() function.
• Syntax:
len(string)
Example:
string = "Hello, World!"
length = len(string)
print(length) # Output: 13
Anshu Sharma
ANSHU SHARMA
Concatenation of a String
• Concatenation of strings in Python means joining two or more strings
together. This is done using the + operator
• Example:
string1 = "Hello"
string2 = "World"
result = string1 + " " + string2
print(result) # Output: Hello World
Anshu Sharma
ANSHU SHARMA
“a”+”b” # output: ab
“1”+”2” #output:12
“123”+”abc” #output:123abc
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Indexing
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
S=‘aaa’
• Id(s)
• 375269286
S=‘bbb’
• id(s)
• 8789695
• Have different memory location
Anshu Sharma
• S=‘python’ ANSHU SHARMA
• Len(s) # 6
• S(len(s)-1) #n [6-1=5 and in forward indexing n is at 5]
• String=‘wonder’
for ch in string: # one by one character to traverse kia hai
print(ch) #if we want in one line (print(ch,end=‘ ‘)
#output:wonder
Output: print(ch,end=‘$’)
#out:w$o$n$d#e$r
W
O
N
D
E
R
Anshu Sharma
ANSHU SHARMA
• Srting=‘wonder’
• For I in range(0,len(string)) # I me ky aiega index
• Print(i) # out:012345
• Agar hume character print karana hai toh hum jse likhte the s[0]
• Haya bhi print(string[i],end=‘ ‘)
Anshu Sharma
ANSHU SHARMA
String Replication
5*”@” will result into @@@@@
“go”*3 will result into gogogo
• S1=123
• S2=456
• S3=‘abc’
• S4=‘des’
• Print(s1+s2) #579
• Print(s3+s4) #’abcdes’
• Print(s1*s3) #print abc 123 times
• Print(s3*s4) #show error
Anshu Sharma
ANSHU SHARMA
• str=1=“program”
• Str2=“python”
• Str3=“Python”
• Str1==str2 #false
• str1!=str2 #true
• Str2==“python” #true
• Str2>str3 #true
• Str3<str1 #true
Anshu Sharma
ANSHU SHARMA
• A-Z = 65-90
• a-z =97-122
• 0-9 = 48-57
Anshu Sharma
ANSHU SHARMA
• ‘aaa’==‘aaa’ # true
• ‘aab’<‘aaa’ #false
Anshu Sharma
ANSHU SHARMA
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).
• Syntax: name of string[start:stop:step]
s = “welcome"
# Retrieves characters from index 1 to 3: ‘elc'
print(s[1:4])
# Retrieves characters from beginning to index 2: ‘wel'
print(s[:3])
# Retrieves characters from index 3 to the end: ‘come'
print(s[3:])
# Reverse a string
print(s[::-1]) emoclew
Anshu Sharma
ANSHU SHARMA
• Str=‘welcome’
For I in range(len(str));
Print(I,’:’,str[i])
output: 0:w ……so on
• Str=‘welcome’
Str[2:6]
Output: lcom
• Str[1:6:2]
Output: ecm
• Str[1:5:2]
Output: ec
Anshu Sharma
ANSHU SHARMA
• Str[:4]
Output:welc
• Str[2:]
Output: lcome
• Str[1::2]
Output: ecm
• Str[:4]+str[4:]
Output: welcome
• Str[::-1]
Output: emoclew [output in reverse]
Anshu Sharma
ANSHU SHARMA
Deleting a String
s = "GfG"
# Deletes entire string
del s
• 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
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
Anshu Sharma
ANSHU SHARMA
• 2. Using join() Method
The join() method is useful for inserting between elements when splitting a
string.
Example: Insert After a Space
text = "I love Python"
words = [Link](" ") # Split into a list: ["I", "love", "Python"]
new_text = " ".join([words[0], "really", words[1], words[2]]) # Insert "really"
print(new_text)
# Output: "I really love Python“
Explanation:
split(" ") → Converts string into a list: ["I", "love", "Python"]
" ".join([...]) → Joins words back with a space " " between them.
Anshu Sharma
ANSHU SHARMA
3. Using replace() Method
You can replace a specific word or pattern with a modified version.
Anshu Sharma
ANSHU SHARMA
Formatting 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
Anshu Sharma