In Python, a string of required formatting can be achieved by different methods. Some of them are; 1) Using % 2) Using {} 3) Using Template Strings In this article the formatting using % is discussed. The formatting using % is similar to that of 'printf' in C programming language. %d - integer %f - float %s - string %x - hexadecimal %o - octal The below example describes the use of formatting using % in Python.
# Python program to demonstrate the use of formatting using %# Initialize variable as a stringvariable='15'string="Variable as string =%s"%(variable)print(string)# Printing as raw data# Thanks to Himanshu Pant for thisprint("Variable as raw data =%r"%(variable))# Convert the variable to integer# And perform check other formatting optionsvariable=int(variable)# Without this the below statement# will give error.string="Variable as integer =%d"%(variable)print(string)print("Variable as float =%f"%(variable))# printing special characters using their ASCII values# For example, 'm' corresponds to ASCII value 109print("Variable as printing with special char =%c"%(109))print("Variable as hexadecimal =%x"%(variable))print("Variable as octal =%o"%(variable))
Variable as string = 15Variable as raw data = '15'Variable as integer = 15Variable as float = 15.000000Variable as printing with special char = mVariable as hexadecimal = fVariable as octal = 17...
K