Signup/Sign In
LAST UPDATED: OCTOBER 30, 2018

String Formatting In Python

    In this article, we are going to learn about String formatting in Python. String formatting is used to convert a string in a format that you want.


    Introduction To Strings In Python

    String: It is a set of characters enclosed in single, double or triple quotes in Python.

    Examples: 'StudyTonight', "StudyTonight", '''StudyTonight'''

    Python provides many string functions to perform various operations on a string variable. You can easily find these in the official documentation. For now, let's dive into the main concept of String formatting.




    String Formatting

    Python uses C-style formatting to create new, formatted strings. Percent % is used in the String formatting. Let's see an example,

    >>> name = 'StudyTonight'
    >>> print('Name: %s' % (name))
    
    # Output
    Name: StudyTonight

    As you can se in the example above, we used %s, to print a string. Similarly, you have to use %d for int and %f for floats and other for different types of data types same just like in C language.

    >>> name = 'StudyTonight'
    >>> no = 255462
    >>> print('Weekly Users of %s is %d' % (name, no))
    
    # Output
    Weekly Users of StudyTonight is 15462



    Using the Format Method

    Let's see the syntax first.

    '{}'.format(variable_name)

    It will print a string value stored in the variable you pass to the format method.

    Time for an example:

    >>> name = 'StudyTonight'
    >>> print('{}'.format(name))
    
    # Output
    StudyTonight

    You can also print a long sentence without any confusion.

    >>> city = 'Nellore'
    >>> print('I am from {}'.format(city))
    
    # output
    I am from Nellore

    Now, we'll see how to print a string using the index or numbering.

    >>> print('{0} and {1}'.format('first', 'second'))
    first and second
    
    >>> print('{1} and {0}'.format('first', 'second'))
    second and first

    The above example clarifies that the first parameter of format method will print at the lowest number, starting from 0. In simple words, it follows the ascending order to write all variables.

    Now, we'll see how to print strings using variable names.

    >>> print('Website: {website}, Name: {name}'.format(name = 'hafeezulkareem', website = 'geeksbro'))
    Website: geeksbro, Name: hafeezulkareem



    Conclusion

    Hope you learned something new today. If you have doubts regarding the tutorial, mention them in the comment section.

    I am a Computer Science Student. I am interested in Programming. I love to know about new technologies.
    IF YOU LIKE IT, THEN SHARE IT
    Advertisement

    RELATED POSTS