str1="Welcome "
str2=" to "
str3=" Python "
str4=" Your student id = "
id=5
print(" Hi {2} {1} {0} ".format(str1,str2,str3))
print(" Hi {0} {1} ".format(str4,id))
Output is here
Hi Python to Welcome
Hi Your student id = 5
Correct the first line to get proper sequnce of words
Right align
name='My Name'
age=5
print("Name {:>25s}, Age {:2d}".format(name,age))
Now the name variable will align right ( within the 25 char space )
Name My Name, Age 5
Printing decimal upto 2 places using format
my_str="Mr ABCD"
avg=356.23456
id=5
name="Welcome to Python"
print("Hi {}, Your id = {}, Your Average ={:.2f})".format(my_str,id,avg))
Output is here
Hi Mr ABCD, Your id = 5, Your Average =356.23)
end
Python adds one line break ( default value of end='\n' ) after each print command, we can remove the line break ( Watch the end='' within the print ())
my_str="Mr ABCD"
avg=356.23456
id=5
name="Welcome to Python"
print("Hi {}, Your id = {} ".format(my_str,id),end='')
print("Your Average ={:.2f})".format(avg))
output is here
Hi Mr ABCD, Your id = 5 Your Average =356.23)
We can use end to print any string at the end of the output. Check here how we used end='...' to print dots after the number.
for i in range (4):
print(i,end='...')
Output
0...1...2...3...
sep
We can add a separator in between strings
print('welcome','to','plus2net', sep='-')
Output
welcome-to-plus2net
Multiple strings with +
print('Welcome '+ 'to '+'plus2net')
Output
Welcome to plus2net
String and Integer
We can't print string with integer, this will generate error. TypeError: must be str, not int
with open('my_file.txt', mode='w') as fob:
print('hello world', file=fob)
This will create my_file.txt file in same directory and write 'hello world' to it.
Printing using variables inside string
a=2
b="welcome"
c="Python"
print("Hello ",b," to ", c )
Output is here
Hello welcome to Python
Using escape char
Let us print I can't travel by bus
print(' I can\'t travel by bus')
We used escape char \ inside the word can't to print single quote instead of using as string termination.
We can use special char \ inside our string without using as escape char by adding r before the quotes
print(r"C:\MyDocument\python\test.py")
Here \t is not considered as Tab and the out put is here