Formating String In Python
Strings in Python are basically arrays of Unicode character bytes and can be represented by enclosing a sequence of characters within single or double-quotes. We can perform concatenation operation on strings using "+" (operator). For examplea='dynamic' b='programming' print(a+b)
The concatenation of a string and other data types is not possible by the "+" operator. For example
a=300 b='is a number' print(a+b) # Will Raise an error.
The format() Method
To combine a string and some other data type we can use format() method. We can use curly brackets {} as placeholders for other Python data type values.
For example,
#concatenation number1=300 #print('hello'+300)# ERROR NOT POSSIBLE print('1. format() method======================') str1='we have {} line of codes' print(str1.format(number1)) #OR print('2. format() method======================') number2=500 str2='we have {} line of codes and {} are still left to code' print(str2.format(number1,number2)) # We can use character in string which are illegal touse in string using escape characters. print("She asked ,\"hello, are you Steve?\" ") Output: 1. format() method====================== we have 300 line of codes 2. format() method====================== we have 300 line of codes and 500 are still left to code She asked ,"hello, are you Steve?"