DEV Community

Tejeswararao123
Tejeswararao123

Posted on

Strings, Lists and OOPS in Python

String Methods

isupper()

  • Returns True if all the characters in a string are in uppercase ### Example
a = "Hello"
b="HI"
print(a.isupper()) # False
print(b.isupper()) # True
Enter fullscreen mode Exit fullscreen mode

islower()

  • Returns True if all the characters in a string are in lowercase ### Example
a = "hello"
b="HI"
print(a.islower()) # True
print(b.islower()) # False
Enter fullscreen mode Exit fullscreen mode

isalnum()

  • Returns True if the string contains only alphabetical letters and digits.
a = "hello5 4 3"
b="HI567hello"
print(a.isalnum()) # False 
print(b.isalnum()) # True
Enter fullscreen mode Exit fullscreen mode

count():

a="hi hello how are you hello"
print(a.count("hello")) # 2
print(a.count("h")) # 4

isdigit():

  • Returns True if all characters are digits

capitalize()

  • Change the case first character in a string to upper case
name = 'python'
# syntax
name_cap = name.capitalize()
print(name_cap) # Python
Enter fullscreen mode Exit fullscreen mode

upper():

  • Change the cases of all characters of a string to uppercase
a = "hi hello!"
a = a.upper()
print(a) # HI HELLO!
Enter fullscreen mode Exit fullscreen mode

lower():

  • Change the cases of all characters of a string to lowercase
a = "HI HELLO!"
a = a.lower()
print(a) # hi hello!
Enter fullscreen mode Exit fullscreen mode

swapcase()

  • swap the cases of all characters in a string. string = 'Who Are You?' after_swapcase = string.swapcase() print(after_swapcase) # wHO aRE yOU?
greeting = "Happy birthday"
index = greeting.index('ppy')
print(index)  # 2
Enter fullscreen mode Exit fullscreen mode

replace():

  • Replace all the occurrences with another string
a = 'i am from Andhrapradesh'
b= a.replace('Andhrapradesh', 'Delhi')
print(b) # 'i am from Delhi'
Enter fullscreen mode Exit fullscreen mode

String slicing:

returns a substring from the original string

Example

a = "Hello Raj"
b = a[0:5]
print(b) # Hello
Enter fullscreen mode Exit fullscreen mode

startswith()

  • Returns true if the string starts with a given string
a = "hi hello how are you"
print(a.startswith("hi")) # True
Enter fullscreen mode Exit fullscreen mode

endswith()

  • This method returns True if the string ends with the given string
a = "hi hello how are you"
print(a.endswith("you")) # True
Enter fullscreen mode Exit fullscreen mode

strip():

  • This method removes specified characters from the string by default it removes spaces
a = ";' hello ';;'"
print(a.strip("'; ")) # hello
Enter fullscreen mode Exit fullscreen mode

split():

  • splits the given strings into a list of words a="hi hello" print(a.split()) # ['hi', 'hello']

List methods

join()

  • This method joins the list of elements with a separator
a = ["hi","hello"]
b=" ".join(a)
print(b) # hi hello
Enter fullscreen mode Exit fullscreen mode

slicing

  • This method returns the sliced list
a=[2,3,4,5,6,7,8,9]
b=a[1:4]
print(b) # [3,4,5]
Enter fullscreen mode Exit fullscreen mode

append():

  • Add passed argument to the end of the list
a=[12,42,23,34,55]
a.append(19)
print(a)  # [12,42,23,34,55,19]
Enter fullscreen mode Exit fullscreen mode

del

  • delete element specified index
a=[2,3,4,5,6]
del a[3]
print(a) # [2,3,4,6]
Enter fullscreen mode Exit fullscreen mode

clear()

delete all elements

a=[2,3,4,5,6]
a.clear()
print(a) # []
Enter fullscreen mode Exit fullscreen mode

count():

  • This method returns the number of occurrences of the given element in the list
a=[2,3,4,5,6,3,3,3]
y=a.count(3)
print(y) # 4
Enter fullscreen mode Exit fullscreen mode

extend():

  • Add items iterable to the end of the list
a=[2,3,4,5,6]
a.extend([7,9])
print(a) # [2,3,4,5,6,7,9]
Enter fullscreen mode Exit fullscreen mode

index()

  • This method returns the index of the first occurrence given value in the list
a=[3,4,5,6,7]
index=a.index(5)
print(index) # 2
Enter fullscreen mode Exit fullscreen mode

insert()

  • This method insert an element at the given position in the list.
a = [3,5,6,7]
a.insert(1,4)
print(a) # [3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode

pop() By default removes the last element else at a specified index

a = [3,5,6,7]
a.pop(0)
print(a) # [5,6,7]
Enter fullscreen mode Exit fullscreen mode

reverse()

  • reverse the order of elements
a = [3,5,6,7]
a.reverse()
print(a) # [7, 6, 5, 3]
Enter fullscreen mode Exit fullscreen mode

sort()

  • sorts the list into ascending or descending order
a =[2,3,6,4,5]
a.sort()
print(a) # [2, 3, 4, 5, 6]
# to sort the list in descending order
a =[2,3,6,4,5]
a.sort(reverse=True)
print(a) # [6, 5, 4, 3, 2]
Enter fullscreen mode Exit fullscreen mode

OOP

  • OOP is a way of approach to building good software that make users and developers happy.
  • We achieve the above using classes and functions
  • Using classes we create instances
  • Class is used to bundling of properties and methods(functions)

  • Class functions is a synonym for methods

  • Class – a blueprint for an instance with exact behavior.

  • Object – one of the instances of the class, performs functionality defined in the
    class.

  • Type – indicates the class the instance belongs to

  • Attribute – Any object value: object.attribute

  • Method – a “callable attribute” defined in the class

  • Class attributes are the attributes that are not specific to instance, common for all

init method in class

  • This method is used to create an instance with some specific set of properties
  • It is a constructor of the class.

Creating a class and its functions

The following functions are achieved in the following class

  • Accessing modifying the instance attribute and class attributes
class MyClass():
    hi=10
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def print_my_name(self):
        print(f"Your name is {self.name}")

    def print_my_age(self):
        print(f"Your age is {self.age}")

    def change_my_age(self,age):
        self.age=age

obj = MyClass("Tejeswar",23)
obj.print_my_name() # Your name is Tejeswar
obj.print_my_age()  # Your age is 23
obj.change_my_age(25)
obj.print_my_age() # Your age is 25
print(obj.hi)
obj.hi=20
print(obj.hi) # 20
print(MyClass.hi) # 10
MyClass.hi=30 
print(MyClass.hi) # 30
print(obj.hi) # 20
Enter fullscreen mode Exit fullscreen mode

Features

Encapsulation means bundling related properties and methods

Inheritance

  • Here we can inherit the methods from the parent class by extending our class to the parent class ### Polymorphism
  • We can have the same names for different functions to avoid overriding we have to call with the prefix super()

There are three types of methods in class

Instance Methods:

  • Instance methods can access all attributes of the instance and take self as a parameter.
  • These methods are accessed by instances
class Cart:
   def __init__(self):
       self.items = {}
   def add_item(self, item_name,quantity):
       self.items[item_name] = quantity
   def display_items(self):
       print(self.items) # {'book': 3}

a = Cart()
a.add_item("book", 3)
a.display_items()

Enter fullscreen mode Exit fullscreen mode

Class Methods:

  • Methods that need access to class attributes but not instance attributes are marked as Class Methods.
  • For class methods, we send cls as a parameter indicating we are passing the class.
  • These methods are accessed through classes
class Cart:
   flat_discount = 0
   @classmethod
   def update_flat_discount(cls, new_flat_discount):
       cls.flat_discount = new_flat_discount

Cart.update_flat_discount(25)
print(Cart.flat_discount) # 25

Enter fullscreen mode Exit fullscreen mode

Static Method:

  • Usually, static methods are used to create utility functions that make more sense to be part of the class.
  • @staticmethod decorator marks the method below it as a static method.
  • These methods are accessed through classes
class Cart:
   @staticmethod
   def greet():
       print("Good morning") # Good morning

Cart.greet()
Enter fullscreen mode Exit fullscreen mode

Top comments (0)