Thursday, February 6, 2020

String Formatting In Python

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 example

The concatenation of a string and other data types is not possible by the "+" operator. For example

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,

#print('hello'+300)# ERROR NOT POSSIBLE

print('1. format() method======================')
str1='we have {} line of codes'
print('2. format() method======================')
str2='we have {} line of codes and {} are still left to code'

# We can use character in string which are illegal touse in string using escape characters.
print("She asked ,\"hello, are you Steve?\" ")

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?"

Escape characters

For the purpose of printing special characters, and escape sequence there are following escape characters available in Python.

Escape characters in Python