0% found this document useful (0 votes)
9 views24 pages

Module 3

This document covers dictionaries and strings in Python, detailing the dictionary data type, its features, operations, and real-world applications. It also discusses string manipulation, including string literals, escape characters, indexing, slicing, and methods for handling strings. Additionally, it introduces pretty printing and nested data structures, along with practical examples and exercises.

Uploaded by

nonen0886
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)
9 views24 pages

Module 3

This document covers dictionaries and strings in Python, detailing the dictionary data type, its features, operations, and real-world applications. It also discusses string manipulation, including string literals, escape characters, indexing, slicing, and methods for handling strings. Additionally, it introduces pretty printing and nested data structures, along with practical examples and exercises.

Uploaded by

nonen0886
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

Dictionaries & Strings

Module – 3
Dictionaries and Structuring Data: The Dictionary Data Type, Pretty Printing, Using Data
Structures to Model Real-World Things.
Manipulating Strings: Working with Strings, Putting Strings Inside Other Strings, Useful
String Methods, Numeric Values of Characters with the ord() and chr() Functions, Coping and
Pasting Strings with the pyperclip Module,
Project: Multi-Clipboard Automatic Messages.

The Dictionary Data Type


Introduction:
 A dictionary is a collection of key-value pairs.
 It is unordered, mutable, and indexed by keys (not positions like lists).
Features of Dictionary:
Ø Unordered (Python 3.6+ maintains insertion order, but logically still unordered).
Ø Mutable – You can change, add, or remove key-value pairs.
Ø Indexed by keys, not positions.
Ø Keys must be unique (no duplicates allowed).
Ø Keys must be immutable types (e.g., int, str, tuple).
Ø Values can be of any data type, including lists, other dictionaries, etc.
Syntax:
dictionary_name = { key1: value1, key2: value2, key3: value3 }
Ø Each item is a key-value pair separated by a colon (:).
Ø Items are separated by commas (,).
Ø The entire dictionary is enclosed in curly braces {}.

Example:
student_details = {
"name":"BMSIT",
"Roll_No":"1BY24CS100",
"PIN":560119
}
Dept. of CSE 1
Dictionaries & Strings

Here,
Name, Roll_NO, and PIN are keys,
BMSIT, 1BY24CS100, and 560119 are values.
Valid Keys Examples:
my_dict = {
101: "BMSIT", # int
"name": "BMS", # str
(1, 2): "Tuple Key" # tuple
}
Invalid Keys Examples
my_dict = {
[1, 2]: "List Key", # ❌ list is mutable
{1: "a"}: "Dict Key" # ❌ dict is mutable
}
# This will raise a TypeError

Real-Time Applications:
 Storing Contact Information (Phone Book)
 Student Marks Record
 E-commerce Product Prices
 Employee Details
 Website Login Info (for simulation, not real storage)
Basic Dictionary Operations:
Operation Example Description
Add Item dict["newkey"] = value Add a new key-value pair
Change the value for an
Update Value dict["key"] = new_value
existing key
Delete Key del dict["key"] Remove key-value pair
Get Keys [Link]() Returns list of all keys
Get Values [Link]() Returns list of all values
Check Key Exists "key" in dict Returns True/False
Loop Through for key, value in
Iterate key-value pairs
Items [Link]():

Dept. of CSE 2
Dictionaries & Strings

Key Differences Between Lists and Dictionaries:


Feature List Dictionary
Definition Ordered collection of items Unordered collection of key-value pairs
Syntax my_list = [10, 20, 30] my_dict = {"name": "Tushar"}
Access Method By index (position) By key
Index Type Integer-based index (0, 1, Key can be string, number, or tuple
2...)
Mutability Mutable (can change items) Mutable (can change, add, delete pairs)
Order Ordered (maintains item Unordered (in logic; insertion order
order) kept since Python 3.7)
Duplicates Yes (same value can appear Keys must be unique; values can repeat
Allowed? multiple times)
Use Case Storing a collection of Storing data with labels or relationships
similar items
Example [1, 2, 3] {"roll": 101, "name": "Tushar"}
Access Example my_list[0] → 1 my_dict["name"] → "Tushar"

To access values in a dictionary:


Ø Using Square Brackets []:
 Directly accesses the value for a key (error if missing).
Syntax:
dict[key]
Example:
>>> student_details = {
'name':"BMSIT",
'[Link]':184,
'CGPA': 7.2
}
>>> type(student_details)
<class 'dict'>
>>> student_details['CGPA']
7.2

Dept. of CSE 3
Dictionaries & Strings

>>> student_details['PERC']
Traceback (most recent call last):
File "<pyshell#57>", line 1, in <module>
student_details['PERC']
KeyError: 'PERC'

Ø Using get() Method:


 Safely gets the value; returns None if key missing.
Syntax:
[Link](key,[option])
Example:
>>> student_details.get('name')
'BMSIT'
>>> student_details.get('PIN') # No Error
Note:
 Returns default value if key is not found.
>>> student_details.get('PIN','N/A')
'N/A'

Ø Using a Loop to Access All Items:


 Loops through keys and accesses corresponding values.
Example:
>>> for key in student_details:
print("%8s"%key, student_details[key])
OUTPUT:
name BMSIT
[Link] 184
CGPA 7.2
>>> for key, value in student_details.items():
print(key, value)
OUTPUT:
name BMSIT
[Link] 184
CGPA 7.2
Dept. of CSE 4
Dictionaries & Strings

The keys(), values(), and items() Methods in Dictionaries:


 These methods allow you to access a dictionary's keys, values, or key-value pairs.
 There are three dictionary methods that will return list-like values of the dictionary’s keys,
values, or both keys and values: keys(), values(), and items().
 The values returned by these methods are not true lists; they cannot be modified and do
not have an append() method.
 But these data types (dict_keys, dict_values, and dict_items, respectively) can be used in
for loops.
Syntax:
>>> for key in my_dict.keys():
print(key)
>>> for value in my_dict.values():
print(value)
>>> for key, value in my_dict.items():
print(key, value)
Example:
>>> student = { 'name': 'Tushar',
'roll_no': 101,
'branch': 'CSE',
'marks': 88 }
>>> print([Link]())
# Output: dict_keys(['name', 'roll_no', 'branch', 'marks'])
# Loop through keys
>>> for key in [Link]():
print(key)

>>> print([Link]())
# Output: dict_values(['Tushar', 101, 'CSE', 88])
# Loop through values
>>> for value in [Link]():
print(value)

Dept. of CSE 5
Dictionaries & Strings

>>> print([Link]())
# Output: dict_items([('name', 'Tushar'), ('roll_no', 101),
('branch', 'CSE'), ('marks', 88)])
# Loop through key-value pairs
>>> for key, value in [Link]():
print(f"{key}: {value}")

NOTE:
 keys_list = list([Link]()) # ['name', 'roll_no', 'branch', 'marks']
 values_list = list([Link]())# ['Tushar', 101, 'CSE', 88]
 items_list = list([Link]()) # [('name', 'Tushar'), ('roll_no', 101),
...]

Checking Whether a Key or Value Exists in a Dictionary:


Check Type Syntax Description
Key Exists 'key' in dict Returns True if key is found
Value Exists 'value' in [Link]() Returns True if value is found

Example:
student = {'name': 'Tushar', 'roll_no': 101, 'branch': 'CSE'}
# Check if 'name' key exists
>>> if 'name' in student:
print("Key 'name' exists.")

# Check if 'CSE' is one of the values


>>> if 'CSE' in [Link]():
print("Value 'CSE' exists.")

Dept. of CSE 6
Dictionaries & Strings

The setdefault() Method:


 If the key is present, setdefault() returns its value.
 If the key is missing, setdefault() adds the key with the default value and returns that
default.
Syntax:
[Link](key, default_value)
Example:
>>> student_details.setdefault('Name','BMS')
'BMS'
>>> student_details
{'name': 'BMSIT', '[Link]': 184, 'CGPA': 7.2, 'Name': 'BMS'}
>>> student_details.setdefault('Name','BMSCE')
'BMS'
>>> student_details
{'name': 'BMSIT', '[Link]': 184, 'CGPA': 7.2, 'Name': 'BMS'}

Pretty Printing:
 pprint stands for pretty-print and is used to display complex data structures in a
readable and well-formatted way.
 [Link](object) prints the pretty-formatted output directly to the console.
 [Link](object) returns the pretty-formatted output as a string, useful for
logging or writing to files.
Feature [Link]() [Link]()
Purpose Prints formatted output to console Returns formatted output as a string
Return Value None (prints directly) Formatted string
Use Case Quick debugging or viewing data Storing or logging formatted data
Output Destination Standard output (console) Variable, file, or any string sink
Typical Usage [Link](obj) pretty_str= [Link](obj)
[Link](data) s = [Link](data) stores
Example
prints to screen formatted text
Customization
Accepts width, depth, sort_dicts Accepts same parameters
Parameters

Dept. of CSE 7
Dictionaries & Strings

Example:
import pprint
data = {
'name': 'Tushar',
'skills': ['Python', 'Machine Learning', 'Cybersecurity'],
'projects': [
{'title': 'Website Defacement Detection', 'year':2025},
{'title': 'Quantum AI Framework', 'year': 2024} ]
}
print("Using print():")
print(data)
print("=" * 20)

# [Link]() prints formatted output immediately


print("Using [Link]():")
[Link](data)
print("=" * 20)

# [Link]() returns formatted string for later use


formatted_str = [Link](data)
print("\nUsing [Link]():")
print(formatted_str)
OUTPUT:

Dept. of CSE 8
Dictionaries & Strings

Case Study:
Using Data Structures to Model Real-World Things.
1. A Tic-Tac-Toe Board

Nested Dictionaries and Lists:


 Nesting means placing one data structure inside another (e.g., dictionary inside dictionary,
list inside list).
 Nested Dictionary: A dictionary where some values are dictionaries themselves.
 Nested List: A list where some elements are lists.
 Can combine both, e.g., dictionary containing lists, or lists containing dictionaries.
 Access nested elements using multiple indexing or key lookups:
o For nested dict: dict[key1][key2]
o For nested list: list[index1][index2]
Example:
>>> data = {'person': {'name': 'Bhagat', 'age': 25}}
>>> print(data['person']['name']) # Bhagat
--------------------------------------------------------------
>>> matrix = [[1, 2], [3, 4]]
>>> print(matrix[0][1]) # 2
Questions:
1. List the merits of dictionary over list. Explain keys(), values(), and items().
2. Explain with a programming example to each: get() setdefault().
3. Explain pprint and pformat functions in pprint module with an example.
4. Explain nested dictionary with a programming example.

Dept. of CSE 9
Dictionaries & Strings

MANIPULATING STRINGS
Introduction:
 Text (Strings) is one of the most common data types handled in Python.
 String Concatenation: Use the + operator to join strings.
“Python ” + “Programming” #Python Programming
 String Slicing: Extract specific parts of a string.
>>> text = "Python"
>>> print(text[0:3]) # → 'Pyt'
Working with Strings:
String Literals:
 A string literal is a fixed value of text written directly in your code.
 It is enclosed in quotes: 'single' or "double".
Example:
‘Lists and dictionary are Mutable data types’
“Strings and Tuples are immutable data types”

Escape Character:
 An escape character consists of a backslash (\) followed by the character you want
to add to the string.
Why Use Escape Characters?
To insert characters like:
 Newlines (\n)
 Tabs (\t)
 Quotes inside strings (\' or \")
 Backslashes (\\)
Example:
print('Single quote: \'')
print("Double quote: \"")
print("Backslash: \\")
print("Newline:\nThis is on a new line")
print("Tab:\tThis is after a tab space")
Dept. of CSE 10
Dictionaries & Strings

OUTPUT:

Raw Strings(r):
 You can place an ‘r’ before the beginning quotation mark of a string to make it a raw
string.
 A raw string completely ignores all escape characters and prints any back slash that
appears in the string.
Example:
>>> print("Strings are \nimmutable")
OUTPUT:
Strings are
immutable
>>> print(r"Strings are \nimmutable")
OUTPUT:
Strings are \nimmutable

Multiline Strings with Triple Quotes:


 A multiline string allows you to span text across multiple lines in your code.
 Created using triple quotes:
'''...''' (triple single quotes)
"""...""" (triple double quotes)
Example:
>>> msg = """This is a
multiline string
in Python."""
>>> print(msg)

Dept. of CSE 11
Dictionaries & Strings

Feature Explanation
No need for \n Newlines are included directly
Quotes inside
Single ' or double " quotes can be used inside
allowed
Python doesn't apply usual block indentation rules inside triple-
Ignores indentation
quoted text
Good for docstrings Used to write multi-line documentation for functions/classes

Multiline Comments in Python:


Method Syntax Example Purpose
Single-line # This is a comment Quick remarks or instructions
Multiline string ' ' ' This is a block... ' ' ' Multiline notes/documentation
Docstring " " " Function description " " " Function/class documentation

Indexing and Slicing Strings:


 String as a Sequence Strings behave like lists of characters.
 Each character has a specific index (position), starting from 0.
Example:
text = "Hello, world!"
Character H e l l o , w o r l d !
Index 0 1 2 3 4 5 6 7 8 9 10 11 12

Indexing
 Access a single character using its index:
Example:
>>> print(text[0]) # Output: H
>>> print(text[7]) # Output: w
>>> print(text[-1]) # Output: ! (last character using negative
indexing)

Slicing
 Extract a substring using the syntax: string[start:end]
 The start index is included, but the end index is excluded.

Dept. of CSE 12
Dictionaries & Strings

Example:
>>> print(text[0:5]) # Output: Hello
>>> print(text[7:12]) # Output: world
Omitting indexes:
print(text[:5]) # Output: Hello (from start to index 4)
print(text[7:]) # Output: world! (from index 7 to end)

Length of a String
 Use len() to find the total number of characters (including spaces and symbols).
>>> len("Hello, world!") # Output: 13

Type Syntax Description


Indexing s[0] First character
Negative s[-1] Last character
Slicing s[start:end] Substring (end is not included)
Skip start s[:end] From beginning
Skip end s[start:] Till end

The in and not in Operators with Strings:


 These operators are used to check for the presence or absence of a substring in another
string.
 They return a Boolean value: True or False.
Syntax:
substring in full_string
substring not in full_string
Example:
>>> 'cat' in 'concatenate' # True
>>> 'bat' in 'concatenate' # False
>>> 'hello' not in 'hi there' # True
>>> 'world' in 'hello world' # True
Use Case Example Result
Check if word is in a sentence 'sun' in 'sunshine' True
Validate user input '@' in email True/False
Password contains special chars '#' in password True/False
Keyword filtering 'python' in [Link]() True/False
Dept. of CSE 13
Dictionaries & Strings

Putting Strings Inside Other Strings:


 Putting strings inside other strings is a common operation in programming.
Method Example
f-Strings f"Hello, {name}!"
[Link]() "Hello, {}!".format(name)
Concatenation "Hello, " + name + "!"
Percent Formatting "Hello, %s!" % name

Example:
>>> name = "BMSIT&M"
>>> print(f"Hello, {name}!")
Hello, BMSIT&M!
>>> print("Hello, %s" % name)
Hello, BMSIT&M
>>> print("Hello,{}".format(name))
Hello,BMSIT&M
>>> print("Hello," + name + "!")
Hello,BMSIT&M!

Dept. of CSE 14
Dictionaries & Strings

Useful String Methods:


 String methods are built-in functions in Python that allow you to analyze, modify, or
transform string values easily.
 For example, changing case, finding substrings, or splitting text.

The upper(), lower(), isupper(), and islower() Methods:


 The upper() and lower() string methods return a new string where all the letters in
the original string have been converted to uppercase or lowercase, respectively.
 Non-letter characters in the string remain unchanged.
Method Definition Example Output
Converts all letters to
'PYTHON
upper() uppercase; non-letters "Python 3.10!".upper()
3.10!'
unchanged
Converts all letters to
'python
lower() lowercase; non-letters "Python 3.10!".lower()
3.10!'
unchanged
 Note that these methods do not change the string itself but return new string
values.
 If you want to change the original string, you have to call upper() or lower() on the
string and then assign the new string to the variable where the original was stored.
Example:
>>> a="Python 3.10!"
>>> a=[Link]()
>>> a
'PYTHON 3.10!'
>>> a=[Link]()
>>> a
'python 3.10!'
 The upper() and lower() methods are helpful if you need to make a case-insensitive
comparison.
Example: The strings 'great' and 'GREat' are not equal to each other.
Dept. of CSE 15
Dictionaries & Strings

 The isupper() and islower() methods will return a Boolean True value if the
string has atleast one letter and all the letters are uppercase
or lowercase, respectively. Otherwise, the method returns False.
Method Definition Example Output
"HELLO".isupper() True
Returns True if the string contains
"Hello".isupper() False
isupper() at least one letter and all letters
"123!".isupper()
are uppercase; else False. False
(no letters)
"hello".islower() True
Returns True if the string contains
"Hello".islower() False
islower() at least one letter and all letters
"123!".islower()
are lowercase; else False. False
(no letters)

The isX() Methods:


Method Definition Example Output
Returns True if the string "Python".isalpha() True
consists only of letters "Python3".isalpha() False
isalpha()
and is not empty; "".isalpha() False
otherwise False. "Hello World".isalpha() False
"Python3".isalnum() True
Returns True if the string
"Python 3".isalnum() False
consists only of letters
isalnum() "12345".isalnum() True
and numbers and is not
"".isalnum() False
empty; otherwise False.
"Hello!".isalnum() False
"12345".isdecimal() True
Returns True if the string
"123.45".isdecimal() False
consists only of decimal
"Ⅷ".isdecimal() False
isdecimal() numeric characters and
"".isdecimal() False
is not empty; otherwise
False
False. "123a".isdecimal()

Dept. of CSE 16
Dictionaries & Strings

Method Definition Example Output


Returns True if the string " \t\n".isspace() True
consists only of " a ".isspace() False
whitespace characters
isspace()
(spaces, tabs, newlines)
"".isspace() False
and is not empty;
otherwise False.
Returns True if each "Hello World".istitle() True
word in the string starts "Hello world".istitle() False
with an uppercase letter "HELLO WORLD".istitle() False
istitle()
followed by only
lowercase letters; "123 Hello".istitle() True
otherwise False.

 The isX() string methods are helpful when you need to validate user input.
Example:
The following program repeatedly asks users for their age and a password until they provide
valid input.
while True:
print('Enter your age:')
age = input()
if [Link]():
break
print('Please enter a number for your age.')

while True:
print('Select a new password (letters and numbers only):')
password = input()
if [Link]():
break
print('Passwords can only have letters and numbers.')

Dept. of CSE 17
Dictionaries & Strings

OUTPUT
Enter your age:
forty two
Please enter a number for your age.
Enter your age:
42
Select a new password (letters and numbers only):
secr3t!
Passwords can only have letters and numbers.
Select a new password (letters and numbers only):
secr3t

The startswith() and endswith() Methods:


 The startswith() and endswith() methods return True if the string value they are
called on begins or ends (respectively) with the string passed to the method;
otherwise, they return False.

Method Definition Example Output


Returns True if "Python".startswith("Py") True
the string begins
startswith() with the specified
substring; "Python".startswith("thon") False
otherwise False.
Returns True if "Python".endswith("on") True
the string ends
endswith() with the specified
substring; "Python".endswith("Py") False
otherwise False.
 These methods are useful alternatives to the == equals operator if you need to check only
whether the first or last part of the string, rather than the whole thing, is equal to another
string.
print("Python".startswith("Py")) # True
print("Python".startswith("thon")) # False
print("Python".endswith("on")) # True
print("Python".endswith("Py")) # False

Dept. of CSE 18
Dictionaries & Strings

The join() and split() Methods:


 The join() method is useful when you have a list of strings that need to be joined together
into a single string value.
 The join() method is called on a string, gets passed a list of strings, and returns a string.
The returned string is the concatenation of each string in the passed-in list.
Syntax:
separator_string.join(iterable)

 The split() method does the opposite:


 It’s called on a string value and returns a list of strings.
Syntax:
[Link](separator, maxsplit)
Here,
 separator (optional): The delimiter to split the string
on (default is any whitespace)
 maxsplit (optional): The maximum number of splits to
perform

Method Definition Example Output


Joins elements of a list into " ".join(["Hello",
'Hello World'
"World"])
a single string using the
join()
string it’s called on as a "-".join(["2025", "05",
'2025-05-27'
"27"])
separator.
Splits a string into a list ['Hello',
"Hello World".split()
'World']
using the given separator
split()
(default is space) and "2025-05-27".split("-") ['2025', '05',
'27']
returns a list of substrings.

Dept. of CSE 19
Dictionaries & Strings

Splitting Strings with the partition() Method:


Method Definition Example Output
Splits a string at the first "Python is ('Python
occurrence of the specified fun".partition ', 'is', '
separator, returning a tuple of ("is") fun')
3 parts: (before, separator,
partition()
after).
If the separator is not found, "Hello".partit ('Hello',
returns a tuple with the original ion("xyz") '', '')
string and two empty strings.

Comparison: split() vs partition()


Feature split() partition()
Splits a string into a list using a Splits a string into a tuple: (before,
Purpose
delimiter separator, after)
Return Type List of strings Tuple of 3 strings
All or maxsplit occurrences of
Splits At First occurrence of the separator only
the separator
Separator If not found, returns the whole If not found, returns
Found? string as a single list element (original_string, '', '')
Number of Variable (depends on content &
Always 3 parts
Parts maxsplit)
"a-b-c".split("-") → "a-b-c".partition("-") →
Example
['a', 'b', 'c'] ('a', '-', 'b-c')
When you want multiple parts When you need to divide into exactly 3
Use Case
or use maxsplit parts

Dept. of CSE 20
Dictionaries & Strings

Justifying Text with the rjust(), ljust(), and center() Methods


 The rjust() and ljust() string methods return a padded version of the string they are
called on, with spaces inserted to justify the text.
 The first argument to both methods is an integer length for the justified string.
Syntax:
[Link](width, fillchar=' ')
[Link](width, fillchar=' ')
[Link](width, fillchar=' ')
Method Definition Example Output
Returns a right-
justified string of
rjust(width) given width, padded "Python".rjust(10) ' Python'
with spaces on the
left.
Returns a left-
justified string of
ljust(width) given width, padded "Python".ljust(10) 'Python '
with spaces on the
right.
Returns a centered
string of given
center(width) width, padded with "Python".center(10) ' Python '
spaces equally on
both sides.

Dept. of CSE 21
Dictionaries & Strings

Removing Whitespace with the strip(), rstrip(), and lstrip()


Methods:
 Sometimes you may want to strip off whitespace characters (space, tab, and newline)
from the left side, right side, or both sides of a string.

strip() Method
 Removes leading and trailing whitespace (spaces, tabs, newlines) from a string.
Example:
>>> text = " Hello, World! \n"
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello, World!'
NOTE:
In Python, repr() stands for "representation" — specifically,
it returns a string that represents the object in a way that is
usually suitable for debugging and development.

lstrip() Method
 Removes only leading (left-side) whitespace.
Example:
>>> text = " Hello"
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello'

rstrip() Method
 Removes only trailing (right-side) whitespace.
Example:
>>> text = "Hello "
>>> cleaned = [Link]()
>>> print(repr(cleaned)) # 'Hello'

Dept. of CSE 22
Dictionaries & Strings

Numeric Values of Characters with the ord() and chr()Functions:


 The text characters in Python are represented internally using Unicode, and each character
maps to a specific numeric value called a Unicode code point.
 To work with these numeric values, Python provides two very useful built-in functions:
ord() and chr().
ord() — Ordinal Value (Unicode Code Point)
 This function takes a single character (string of length 1) and returns its Unicode code
point (an integer).
Example:
>>> print(ord('A')) # 65
>>> print(ord('a')) # 97
>>> print(ord('😊')) # 128522
>>> print(ord('0')) # 48
>>> print(ord(' ')) # 32
>>> print(ord('\0')) # 0
chr() — Character from Unicode Code Point
 This function takes an integer (Unicode code point) and returns the corresponding
character.
Example:
>>> print(chr(65)) # 'A'
>>> print(chr(97)) # 'a'
>>> print(chr(128522)) # '😊'

Understanding ord() and chr() is important for:


Ø Encryption and encoding algorithms
Ø Sorting characters by their values
Ø Understanding how strings are stored and processed internally.

Dept. of CSE 23
Dictionaries & Strings

Copying and Pasting Strings with the pyperclip Module:


 The pyperclip module has copy() and paste() functions that can send text to and
receive text from your computer’s clipboard.
 The pyperclip module is a super handy Python library that allows your script to interact
with your system clipboard, just like how you manually copy (Ctrl+C) and paste (Ctrl+V)
text.
Before using it, install the module (if not already installed):
pip install pyperclip
Example:
import pyperclip
[Link]("Hello from Python!")

text = [Link]()
print("Clipboard contains:", text)
OUTPUT:
Clipboard contains: Hello from Python!
# You can now paste it anywhere (e.g., Notepad,
browser) using Ctrl + V.

Dept. of CSE 24

You might also like