Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python Methods

The document provides an overview of various Python methods for strings, lists, dictionaries, sets, and file handling, along with commonly used built-in functions. Each method is described with its purpose and includes examples for clarity. This serves as a quick reference guide for Python programming.

Uploaded by

Aboshareeha Amro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Methods

The document provides an overview of various Python methods for strings, lists, dictionaries, sets, and file handling, along with commonly used built-in functions. Each method is described with its purpose and includes examples for clarity. This serves as a quick reference guide for Python programming.

Uploaded by

Aboshareeha Amro
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

Python

String Methods

1. str.upper() / str.lower()
o Purpose: Converts all characters in the string to uppercase or lowercase,
respectively.
o Example: "hello".upper() → "HELLO"; "WORLD".lower() → "world"
2. str.capitalize()
o Purpose: Capitalizes only the first character of the string while converting the rest
to lowercase.
o Example: "hello world".capitalize() → "Hello world"
3. str.find(sub)
o Purpose: Searches for the first occurrence of the specified substring ( sub).
Returns the index if found, else returns -1.
o Example: "hello world".find("world") → 6
4. str.replace(old, new)
o Purpose: Replaces all instances of old substring with new substring within the
string.
o Example: "banana".replace("a", "o") → "bonono"
5. str.split(delimiter)
o Purpose: Splits a string into a list based on a specified delimiter. If no delimiter is
specified, it splits at whitespace.
o Example: "apple,banana,pear".split(",") → ["apple", "banana",
"pear"]
6. str.join(iterable)
o Purpose: Joins elements of an iterable (like a list) into a single string, separated
by the string on which join is called.
o Example: ",".join(["apple", "banana", "pear"]) →
"apple,banana,pear"
7. str.strip() / str.lstrip() / str.rstrip()
o Purpose: Removes whitespace (or specified characters) from both ends of a string
with strip, from the left with lstrip, or from the right with rstrip.
o Example: " hello ".strip() → "hello"
Python
List Methods

1. list.append(item)
o Purpose: Adds an item to the end of the list, modifying the list in place.
o Example: fruits = ["apple"]; fruits.append("banana") → ["apple",
"banana"]
2. list.extend(iterable)
o Purpose: Extends the list by adding elements from another iterable, like a list or
set, to the end.
o Example: numbers = [1, 2]; numbers.extend([3, 4]) → [1, 2, 3, 4]
3. list.insert(index, item)
o Purpose: Inserts an item at the specified index, shifting subsequent elements to
the right.
o Example: letters = ["a", "c"]; letters.insert(1, "b") → ["a", "b",
"c"]
4. list.remove(item)
o Purpose: Removes the first occurrence of the specified item from the list; raises
an error if the item is not found.
o Example: fruits = ["apple", "banana", "apple"];
fruits.remove("apple") → ["banana", "apple"]
5. list.pop(index)
o Purpose: Removes and returns the item at the specified index. If no index is
given, it removes the last item.
o Example: numbers = [1, 2, 3]; numbers.pop(1) → 2, numbers becomes
[1, 3]
6. list.sort() / list.reverse()
o Purpose: Sorts the list in place in ascending order (default) with sort or reverses
the order with reverse.
o Example: nums = [3, 1, 2]; nums.sort() → [1, 2, 3]
7. list.index(item)
o Purpose: Returns the index of the first occurrence of the specified item; raises an
error if not found.
o Example: ["a", "b", "c"].index("b") → 1
Python
Dictionary Methods

1. dict.get(key)
o Purpose: Retrieves the value associated with the specified key. Returns None if
the key does not exist (or a default value if provided).
o Example: {"name": "Alice"}.get("name") → "Alice"
2. dict.keys() / dict.values()
o Purpose: keys() returns a view of all keys, while values() returns a view of all
values.
o Example: {"name": "Alice", "age": 30}.keys() → dict_keys(["name",
"age"])
3. dict.items()
o Purpose: Returns a view object containing the dictionary's key-value pairs as
tuples.
o Example: {"name": "Alice", "age": 30}.items() →
dict_items([("name", "Alice"), ("age", 30)])
4. dict.update(other_dict)
o Purpose: Updates the dictionary with key-value pairs from another dictionary.
o Example: d = {"a": 1}; d.update({"b": 2}) → {"a": 1, "b": 2}
5. dict.pop(key)
o Purpose: Removes and returns the value associated with the specified key.
o Example: {"a": 1, "b": 2}.pop("a") → 1
6. dict.clear()
o Purpose: Empties all key-value pairs from the dictionary.
o Example: d = {"a": 1}; d.clear() → {}
Python
Set Methods

1. set.add(item)
o Purpose: Adds an item to the set, if it’s not already present.
o Example: s = {1, 2}; s.add(3) → {1, 2, 3}
2. set.update(iterable)
o Purpose: Adds all items from an iterable (e.g., list) to the set.
o Example: s = {1}; s.update([2, 3]) → {1, 2, 3}
3. set.remove(item)
o Purpose: Removes a specific item from the set; raises an error if the item is not
found.
o Example: s = {1, 2, 3}; s.remove(2) → {1, 3}
4. set.discard(item)
o Purpose: Removes an item if present, but does nothing if the item is not in the
set.
o Example: s = {1, 2, 3}; s.discard(4) → {1, 2, 3}
5. set.union(other_set)
o Purpose: Returns a new set with all items from both sets.
o Example: {1, 2}.union({2, 3}) → {1, 2, 3}
6. set.intersection(other_set)
o Purpose: Returns a new set with items common to both sets.
o Example: {1, 2}.intersection({2, 3}) → {2}
7. set.difference(other_set)
o Purpose: Returns a new set with items unique to the original set.
o Example: {1, 2}.difference({2, 3}) → {1}

File Methods

1. open(filename, mode)
o Purpose: Opens a file with a specified mode ( r for read, w for write, a for append,
etc.).
o Example: file = open("test.txt", "r")
2. file.read() / file.readline() / file.readlines()
o Purpose: read() reads the entire file, readline() reads one line, and
readlines() reads all lines as a list.
o Example: file.read() → "file content"
3. file.write(data)
o Purpose: Writes data to the file, usually used in write or append mode.
o Example: file.write("Hello")
4. file.close()
o Purpose: Closes the file, ensuring all data is properly written.
o Example: file.close()
Python
Commonly Used Built-in Functions

1. len(obj)
o Purpose: Returns the number of items in an object (e.g., characters in a string,
elements in a list).
o Example: len("hello") → 5
2. type(obj)
o Purpose: Returns the type of an object.
o Example: type(5) → <class 'int'>
3. print()
o Purpose: Outputs data to the console.
o Example: print("Hello") → Displays "Hello"
4. range(start, stop, step)
o Purpose: Generates a sequence of numbers from start to stop (exclusive),
incrementing by step.
o Example: list(range(1, 5)) → [1, 2, 3, 4]
5. sum(iterable)
o Purpose: Returns the sum of all items in an iterable, like a list or tuple.
o Example: sum([1, 2, 3]) → 6
6. sorted(iterable)
o Purpose: Returns a sorted list of items from the iterable, without modifying the
original iterable.
o Example: sorted([3, 1, 2]) → [1, 2, 3]

You might also like