Python :F-Strings

In Python, to format output statements you can do in several ways as below.
    • 1. Regular print() using parameter data types
      2. Using .format()
      3. Using F-string

  • I will write small examples using all 3 types.

    1. Regular print() using parameter data types

    In the below example I will define values and print same for 3 most used data types which are int, string, float

    
    >>> a = 10
    >>> b = "Hello"
    >>> c = 98.9
    >>> print("a value is %d b value is %s c value is %f" %(a, b, c))
    a value is 10 b value is Hello c value is 98.900000
    

    If you observe the float this is not what I have defined actually, but we are not without options either, we can restrict how many decimals we want. Check below code

    
    >>> print("a value is %d b value is %s c value is %.2f" %(a, b, c))
    a value is 10 b value is Hello c value is 98.90
    >>> print("a value is %d b value is %s c value is %.3f" %(a, b, c))
    a value is 10 b value is Hello c value is 98.900
    >>>
    

    Next let's do same with .format()

    2. Using .format()

    Using format we can also evaluate expressions while printing, below code snippets cover both normal printing and expressions which are evaluated

    
    >>> a = 10
    >>> b = "Hello"
    >>> c = 98.9
    >>> print("a value is {0}, b value is {1}, c value is {2}".format(a,b,c))
    a value is 10, b value is Hello, c value is 98.9
    >>> print("a value is {a}, b value is {b}, c value is {c}".format(a=a,b=b,c=c))
    a value is 10, b value is Hello, c value is 98.9
    >>> print("a value is {a}, b value is {b}, c value is {c}".format(a=a,b=b,c=c if c > 100 else 0))
    a value is 10, b value is Hello, c value is 0
    
    

    I am not adding any explanation here because the code itself self explanatory.

    Now let's see F-Strings

    >>> f'{a} {b} {c}'
    '10 Hello 98.9'
    >>> f'{a} {b} {c if c > 100 else 0 } '
    '10 Hello 0 '
    >>> print(f'{a} {b} {c if c > 100 else 0 } ')
    10 Hello 0
    
    Hope it helps.

    Thank you.

    0 comments:

    Post a Comment