String Formatting Function Overview

  • Share this:

Code introduction


This function accepts a string and a format type, then returns the string formatted according to the specified format type. Supported format types include uppercase, lowercase, capitalize, and title case.


Technology Stack : String manipulation

Code Type : String formatting function

Code Difficulty : Intermediate


                
                    
def format_string(string, format_type='upper'):
    """
    Format a string based on the specified format type.

    :param string: The string to be formatted.
    :param format_type: The type of formatting to apply. Default is 'upper' for uppercase.
    :return: The formatted string.
    """
    if format_type == 'upper':
        return string.upper()
    elif format_type == 'lower':
        return string.lower()
    elif format_type == 'capitalize':
        return string.capitalize()
    elif format_type == 'title':
        return string.title()
    else:
        return string