methods of different data types in python
ChatGPT said:
ChatGPT
In Python, every data type has its own set of methods. Methods are functions that are specific
to a particular data type and allow you to perform operations on the data. Here's a list of
common data types and their methods:
1. String (str) Methods
Strings are immutable sequences of characters.
Method Description
str.upper() Converts all characters to uppercase.
str.lower() Converts all characters to lowercase.
str.capitalize() Capitalizes the first character of the string.
str.title() Capitalizes the first letter of each word.
str.strip() Removes leading and trailing whitespaces.
str.lstrip() Removes leading whitespaces.
str.rstrip() Removes trailing whitespaces.
str.split() Splits the string into a list based on a delimiter.
str.replace(old, new) Replaces occurrences of a substring with another.
str.find(sub) Returns the index of the first occurrence of a substring.
str.index(sub) Same as find, but raises an error if the substring is not found.
str.count(sub) Counts occurrences of a substring.
str.startswith() Checks if the string starts with a particular prefix.
str.endswith() Checks if the string ends with a particular suffix.
str.isdigit() Checks if the string consists of digits only.
str.isalpha() Checks if the string contains alphabetic characters only.
Example:
python
Copy code
text = "hello world"
print(text.upper()) # HELLO WORLD
print(text.replace("world", "Python")) # hello Python
2. List (list) Methods
Lists are mutable collections of items.
Method Description
list.append(item) Adds an item to the end of the list.
list.extend(iterable) Adds multiple items from an iterable to the list.
list.insert(index, item) Inserts an item at a specific position.
list.remove(item) Removes the first occurrence of an item.
list.pop(index) Removes and returns the item at the given index.
list.index(item) Returns the index of the first occurrence of an item.
list.count(item) Counts the occurrences of an item in the list.
list.sort() Sorts the list in ascending order.
list.reverse() Reverses the order of the list.
list.clear() Removes all elements from the list.
Example:
python
Copy code
nums = [1, 2, 3]
nums.append(4)
print(nums) # [1, 2, 3, 4]
nums.sort(reverse=True)
print(nums) # [4, 3, 2, 1]
3. Tuple (tuple) Methods
Tuples are immutable collections of items.
Method Description
tuple.count(item) Counts the occurrences of an item in the tuple.
tuple.index(item) Returns the index of the first occurrence of an item.
Example:
python
Copy code
t = (1, 2, 3, 2, 1)
print(t.count(2)) # 2
print(t.index(3)) # 2
4. Set (set) Methods
Sets are unordered collections of unique elements.
Method Description
set.add(item) Adds an item to the set.
set.remove(item) Removes an item (raises an error if not found).
set.discard(item) Removes an item (no error if not found).
set.pop() Removes and returns a random item from the set.
Method Description
set.clear() Removes all items from the set.
set.union(set2) Returns the union of two sets.
set.intersection(set2) Returns the intersection of two sets.
set.difference(set2) Returns the difference between two sets.
set.update(set2) Updates the set with elements from another set.
Example:
python
Copy code
s = {1, 2, 3}
s.add(4)
print(s) # {1, 2, 3, 4}
s.remove(2)
print(s) # {1, 3, 4}
5. Dictionary (dict) Methods
Dictionaries store key-value pairs.
Method Description
dict.keys() Returns all the keys in the dictionary.
dict.values() Returns all the values in the dictionary.
dict.items() Returns all key-value pairs as tuples.
dict.get(key) Returns the value for a key (or None if missing).
dict.update(other_dict) Updates the dictionary with another dictionary.
dict.pop(key) Removes and returns the value for the given key.
dict.popitem() Removes and returns the last inserted key-value pair.
dict.clear() Removes all items from the dictionary.
dict.setdefault(key, val) Sets a default value for a key if it doesn't exist.
Example:
python
Copy code
d = {"a": 1, "b": 2}
print(d.keys()) # dict_keys(['a', 'b'])
print(d.get("a")) # 1
d.update({"c": 3})
print(d) # {'a': 1, 'b': 2, 'c': 3}
6. Numeric (int, float) Methods
Numeric types include integers and floating-point numbers.
Method Description
int.bit_length() Returns the number of bits to represent the number.
float.is_integer() Checks if the float is equivalent to an integer.
abs(x) Returns the absolute value of x.
round(x, n) Rounds the number x to n decimal places.
pow(x, y) Returns x raised to the power of y.
Example:
python
Copy code
num = -5
print(abs(num)) # 5
print(pow(2, 3)) # 8
print(round(3.14159, 2)) # 3.14
7. Boolean (bool) Methods
Booleans are simple: True or False. They inherit some methods from other data types (like
integers).
Examples:
python
Copy code
print(bool(1)) # True
print(bool(0)) # False
8. General Functions Applicable to Most Data Types
These functions can be used with many data types:
len() – Returns the length of a string, list, tuple, dictionary, or set.
type() – Returns the data type of the object.
id() – Returns the memory address of the object.
sorted() – Returns a sorted version of a list, tuple, or set