Print in Python



Hello people,
We have already seen how to print in Python in the previous post. Still there's more that you can do with print function.
Pass a string with * and integer value. You get it printed the times specified. For example,

>>>print ("Hi " * 3)
Hi Hi Hi

You see Hi is printed 3 times here. If you pass integer this way, the output will be its product. However, in Python 3 and above an integer value is also printed multiple times using this technique.

Printing variables in python is also easy. Just pass the variable name in print method.

>>>n=7
>>>print (n)
7

You can write string along with variables using {} braces. Entire string should be followed by .format function which has variable names to write in place of {}. Values can also be used in .format function. Try this and you will get what I mean.

>>>n = 3
>>>print ("Python {}".format(n) )
Python 3

For a format with multiple parameters they are placed respective of the braces in string. A better option is to use index with {} like {0}, {1} and so. Then literals are taken from format parameters according to the index.

>>>a = 2
>>>b = 3
>>>print ("Python {3} is better than Python {2}".format(1,a,b) )
>>>print ("Without index {} {} {}".format(1,a,b))
Python 3 is better than Python 2
Without index 1 2 3

You might be thinking, "Okay. That's great. But what if I have to use braces {} in my sentence and use other braces {} for formatting?" Easy though. If you are not using format then {} are simply displayed If you are doing it together then double the braces to print them and its done!

>>>print (" {{ }} {}".format(1))
{ } 1

Please share if you find it helpful. If you find any errors in the code feel free to comment and let me know.

Comments

  1. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.
    Python Online training
    Python Course institute in Bangalore

    ReplyDelete

Post a Comment

Did you enjoy reading it? Comment and help me improve.

Popular posts from this blog

Coding Digits

Calculating bits of bits.