Blog

  • Python String Center() Method

    Python center() method alligns string to the center by filling paddings left and right of the string. This method takes two parameters, first is a width and second is a fillchar which is optional. The fillchar is a character which is used to fill left and right padding of the string.

    Python String center() Method

    It has the following syntax:

    center(width[,fillchar])  

    Parameters

    • width (required)
    • fillchar (optional)

    Return Type

    It returns modified string.

    Different Examples for Python String center() Method

    Here, we are going to take several examples to demonstrate the string center() Method in Python.

    Python String Center() Method Example 1: default fill char

    Here, we did not pass second parameter. By default it takes spaces.

    # Python center() function example  
    
    # Variable declaration  
    
    str = "Hello Pythonapp"  
    
    # Calling function  
    
    str2 = str.center(20)  
    
    # Displaying result  
    
    print("Old value:", str)  
    
    print("New value:", str2)

    Output:

    Old value: Hello Pythonapp
    New value: Hello Pythonapp
    

    Python String Center() Method Example 2

    Here, we are providing padding char (optional) parameter as #. See the example.

    # Python center() function example  
    
    # Variable declaration  
    
    str = "Hello Pythonapp"  
    
    # Calling function  
    
    str2 = str.center(20,'#')  
    
    # Displaying result  
    
    print("Old value:", str)  
    
    print("New value:", str2)

    Output:

    Old value: Hello Pythonapp
    New value: ##Hello Pythonapp##
    

    Python String Center() Method Example 3

    Let us take another example to demonstrate the string center() method in Python.

    # Python center() function example  
    
    # Variable declaration  
    
    str = "Hello PythonApp"  
    
    if str == "Hell0 PythonApp":  
    
        str2 = str.center(20,'#')  
    
    else:  
    
        str2 = str.center(20,'!')  
    
    # Displaying result  
    
    print("Old value:", str)  
    
    print("New value:", str2)

    Output:

    Old value: Hello PythonApp
    New value: !!Hello PythonApp!!
  • Python String Casefold() Method

    Python Casefold() method returns a lowercase copy of the string. It is more simillar to lowercase method except it revomes all case distinctions present in the string.

    For example in German, ‘β’ is equivelent to “ss”. Since it is already in lowercase, lowercase do nothing and prints ‘β’ whereas casefold converts it to “ss”.

    Python String casefold() Method Syntax

    It has the following syntax:

    casefold()  

      Parameters

      No parameter is required.

      Return Type

      It returns lowercase string.

      Python Version

      This function was introduced in Python 3.3.

      Different Examples for Python Sring casefold() Function

      Here, we are going to take some examples to demonstrate the working of string casefold() function in Python.

      Python String Casefold() Method Example 1

      Let us take an example to illustrate the string casefold() function in Python.

      # Python casefold() function example  
      
      # Variable declaration  
      
      str = "PYTHONAPP"  
      
      # Calling function  
      
      str2 = str.casefold()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)

      Output:

      Old value: PYTHONAPP
      New value: pythonapp
      

      Python String Casefold() Method Example 2

      The strength of casefold, it not only converts into lowercase but also converts strictly. See an example below ‘β’ is converted into “ss”.

      # Python casefold() function example  
      
      # Variable declaration  
      
      str = "PYTHONAPP - β"  
      
      # Calling function  
      
      str2 = str.casefold()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)

      Output:

      Old value: PYTHONAPP - β
      New value: pythonapp ? ss
      

      Python String Casefold() Method Example 3

      If string is in camelcase, it still converts whole string into lowercase.

      # Python casefold() function example  
      
      # Variable declaration  
      
      str = "PyThOnApP"  
      
      # Calling function  
      
      str2 = str.casefold()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)

      Output:

      Old value: PyThOnApP
      New value: pythonapp
    1. Python String capitalize() Method

      In Python, the capitalize() method is used to convert the first character of the string into uppercase without altering the whole string. It changes the first character only and skips rest of the string unchanged.

      Python String capitalize() Method Syntax

      It has the following syntax:

      capitalize()  

      Parameters

      It does not required any parameter.

      Return Type

      It returns a modified string.

      Different Examples for Python String capitalize() Method

      Here, we are going to take several examples to demonstrate the working of the string capitalize() Method in Python.

      Python String capitalize() Method Example 1

      # Python capitalize() function example  
      
      # Variable declaration  
      
      str = "pythonapp"  
      
      # Calling function  
      
      str2 = str.capitalize()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)

      Output:

      Old value: pythonapp
      New value: Pythonapp
      

      Python String Capitalize() Method Example 2

      What if first character already exist in uppercase.

      # Python capitalize() function example  
      
      # Variable declaration  
      
      str = "Pythonapp"  
      
      # Calling function  
      
      str2 = str.capitalize()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)

      Output:

      Old value: Pythonapp
      New value: Pythonapp
      

      It returns the same string without any alteration.

      Python String Capitalize() Method Example 3

      What if first character is a digit or non-alphabet character? This method does not alter character if it is other than a string character.

      # Python capitalize() function example  
      
      # Variable declaration  
      
      str = "#pythonapp"  
      
      # Calling function  
      
      str2 = str.capitalize()  
      
      # Displaying result  
      
      print("Old value:", str)  
      
      print("New value:", str2)  
      
      print("--------digit---------")  
      
      str3 = "1-tpointtech"  
      
      str4 = str3.capitalize()  
      
      print("Old value:", str3)  
      
      print("New value:", str4)

      Output:

      Old value: #pythonapp
      New value: #pythonapp
      --------digit---------
      Old value: 1-pythonapp
      New value: 1-pythonapp
    2. Python iter() Function

      The python iter() function is used to return an iterator object. It creates an object which can be iterated one element at a time.

      Python iter() Function Syntax

      It has the following syntax:

      iter(object, sentinel)  

      Parameters

      • object: An iterable object.
      • sentinel (optional): It is a special value that represents the end of a sequence.

      Return

      It returns an iterator object.

      Python iter() Function Example

      The below example shows the working of the iter() function in Python.

      # list of numbers  
      
      list = [1,2,3,4,5]  
      
        
      
      listIter = iter(list)  
      
        
      
      # prints '1'  
      
      print(next(listIter))  
      
        
      
      # prints '2'  
      
      print(next(listIter))  
      
        
      
      # prints '3'  
      
      print(next(listIter))  
      
        
      
      # prints '4'  
      
      print(next(listIter))  
      
        
      
      # prints '5'  
      
      print(next(listIter))

      Output:

      1
      2
      3
      4
      5
      

      Explanation:

      In the above example, iter() function converts an list iterable to an iterator.

    3. Python hasattr() Function

      The python hasattr() function returns true if an object has given named attribute. Otherwise, it returns false.

      Python hasattr() Function Syntax

      It has the following syntax:

      hasattr(object, attribute)  

      Parameters

      • object: It is an object whose named attribute is to be checked.
      • attribute: It is the name of the attribute that you want to search.

      Return

      It returns true if an object has given named attribute. Otherwise, it returns false.

      Python hasattr() Function Example

      The below example shows the working of hasattr() function in Python.

      class Employee:  
      
          age = 21  
      
          name = 'Phill'  
      
        
      
      employee = Employee()  
      
        
      
      print('Employee has age?:', hasattr(employee, 'age'))  
      
      print('Employee has salary?:', hasattr(employee, 'salary'))

      Output:

      Employee has age?: True
      Employee has salary?: False
      

      Explanation:

      In the above example, we have created a class named as Employee, then we create the object of the Employee class, i.e., employee. The hasattr(employee, ‘age’) returns the true value as the employee object contains the age named attribute, while hasattr(employee, ‘salary’)) returns false value as the employee object does not contain the salary named attribute.

    4. Python globals() Function

      The python globals() function returns the dictionary of the current global symbol table. A Symbol table is defined as a data structure which contains all the necessary information about the program. It includes variable names, methods, classes etc.

      Python globals() Function Syntax

      It has the following syntax:

      globals()  

      Parameters

      It does not contain any parameters.

      Return

      It returns the dictionary of the current of the current global symbol table.

      Python globals() Function Example

      The below example shows how to modify a global variable using the globals() function in Python.

      age = 22  
      
        
      
      globals()['age'] = 22  
      
      print('The age is:', age)

      Output:

      The age is: 22
      

      Explanation:

      In the above example, we take a variable name(age) and make it as a global variable and this global variable is being modified by using globals() method.

    5. Python getattr() Function

      The python getattr() function returns the value of a named attribute of an object. If it is not found, it returns the default value.

      Python getattr() Function Syntax

      It has the following syntax:

      getattr(object, attribute, default)  

      Parameters

      • object: An object whose named attribute value is to be returned.
      • attribute: Name of the attribute of which you want to get the value.
      • default (optional): It is the value to return if the named attribute does not found.

      Return

      It returns the value of a named attribute of an object. If it is not found, it returns the default value.

      Different Examples for Python getattr() Function

      Here, we are going to discuss several examples for Python getattr() Function.

      Python getattr() Function Example 1

      The below example shows the working of the getattr() function in Python.

      class Details:  
      
          age = 22  
      
          name = "Phill"  
      
        
      
      details = Details()  
      
      print('The age is:', getattr(details, "age"))  
      
      print('The age is:', details.age)

      Output:

      The age is: 22
      The age is: 22
      

      Explanation: In the above example, we take a class named as Details that consists of some variables i.e. age, name etc. and returns the value of named attributes of an object in output.

      Python getattr() Function Example 2

      The below example shows the working of getattr() when named attribute is not found.

      class Details:  
      
          age = 22  
      
          name = "Phill"  
      
        
      
      details = Details()  
      
        
      
      # when default value is provided  
      
      print('The gender is:', getattr(details, 'gender', 'Male'))  
      
        
      
      # when no default value is provided  
      
      print('The gender is:', getattr(details, 'gender'))

      Output:

      The gender is: Male
      AttributeError: 'Details' object has no attribute 'gender'
    6. Python frozenset() Function

      The python frozenset() function returns an immutable frozenset object initialized with elements from the given iterable.

      Python frozenset() Function Syntax

      It has the following Syntax:

      frozenset(iterable)  

      Parameters

      • iterable: An iterable object such as list, tuple etc.

      Return

      It returns an immutable frozenset object initialized with elements from the given iterable.

      Different Examples for Python frozenset() Function 

      Here, we are going to discuss several examples for Python frozenset() function.

      Python frozenset() Function Example 1

      The below example shows the working of the frozenset() function in Python.

      # tuple of letters  
      
      letters = ('m', 'r', 'o', 't', 's')  
      
        
      
      fSet = frozenset(letters)  
      
      print('Frozen set is:', fSet)  
      
      print('Empty frozen set is:', frozenset())

      Output:

      Frozen set is: frozenset({'o', 'm', 's', 'r', 't'})
      Empty frozen set is: frozenset()
      

      Explanation:

      In the above example, we take a variable that consists tuple of letters and returns an immutable frozenset object.

      Python frozenset() Function Example 2

      The below example shows the working of frozenset() with dictionaries.

      # random dictionary  
      
      person = {"name": "Phill", "age": 22, "sex": "male"}  
      
        
      
      fSet = frozenset(person)  
      
      print('Frozen set is:', fSet)

      Output:

      Frozen set is: frozenset({'name', 'sex', 'age'})
    7. Python format() Function

      The python format() function returns a formatted representation of the given value.

      Python format() Function Syntax

      It has the following syntax:

      format(value, format)  

      Parameters

      • value: It is the value that needs to be formatted.
      • format: It is the specification on how the value should be formatted.

      Return

      It returns a formatted representation of the given value.

      Python format() Function Example

      The below example shows a number of formatting with format() function in Python.

      # d, f and b are a type  
      
        
      
      # integer  
      
      print(format(123, "d"))  
      
        
      
      # float arguments  
      
      print(format(123.4567898, "f"))  
      
        
      
      # binary format  
      
      print(format(12, "b"))

      Output:

      123
      123.456790
      1100
      

      Explanation: The above example returns a formatted representation of the values.

    8. Python float() Function

      The python float() function returns a floating-point number from a number or string. A floating-point number, or float, is a mathematical value that contains a decimal point. Floats can be positive or negative and can address both whole numbers and fractional values. In Python, the float() function is utilised to switch a value completely to a float.

      Python float() Function Syntax

      It has the following syntax:

      float(value)  

      Parameters

      • value: It can be a number or string that converts into a floating point number.

      Return

      It returns a floating point number.

      Different Examples for Python float() Function

      Here, we are going to take several examples to demonstrate the Python float() Function.

      Python float() Function Example 1

      The below example shows the working of the float() function in Python.

      # Python example program for float() function in Python  
      
      # for integers    
      
      a = float(2)  
      
      print(a)    
      
          
      
      # for floats    
      
      b = float(" 5.90 ")  
      
      print(b)    
      
          
      
      # for string floats    
      
      c = float("-24.17")  
      
      print(c)    
      
          
      
      # for string floats with whitespaces    
      
      d = float(" -17.15\n ")  
      
      print(d)    
      
        
      
      # string float error    
      
      e = float(" xyz ")    
      
      print(e)

      Output:

      2.0
      5.90
      -24.17
      -17.15
      ValueError: could not convert string to float: ' xyz '
      

      Explanation: In the above example, we have given different types of inputs, like an integer, a float value, and a string value. When the argument is passed to the float() function, the output is returned in the form of a floating value.

      Note: The important point to note is that the float() method converts only integers and strings into floating-point values. All the other arguments, like list, tuple, dictionary, and None values, result in TypeErrors.

      Python float() Function Example 2

      Let us take an example to demonstrate the float() function in Python.

      # Python program for float() function  
      
      # List  
      
      list = float([11, 24, 38, 76, 100])  
      
      # Tuple  
      
      tuple = float(( 10, 20, 30, 40, 50 ))  
      
      # Dictionary  
      
      dictionary = float({ " ram ": 1000, " bheem ": 2000})  
      
      # None  
      
      value = float(None)  
      
        
      
      print(list)  
      
      print(tuple)  
      
      print(dictionary)  
      
      print(value)

      Output:

      TypeError: float() argument must be a string or a number, not ' list '
      TypeError: float() argument must be a string or a number, not ' tuple '
      TypeError: float() argument must be a string or a number, not ' dict '
      TypeError: float() argument must be a string or a number, not ' NoneType '
      

      Conclusion

      To conclude, the float() function in Python is utilised to change a number or a string that addresses a number to a floating-point value. When utilised accurately, the function can assist you with changing information between various mathematical configurations and performing number-crunching tasks that require floating-point accuracy.