Python Tutorial 2-String Formatting in Python

Python Tutorial 2-String Formatting in Python

You want to print “Hello Mr X ” wherein you have created variable name as “Mr X”.

name= "Mr X"
print("Hello, %s!" % name)

Another example, print ” Mr X is 25 years old” where you have to create extra variable name as Age

name= "Mr X"
age=25
print("%s is %d years old " % (name,age))

Now lets understand the meaning of %s and %d and some other useful operator that can be used logically at designated places. These basic operator to defined the type of variable that can be used in place of operator. Here are some basic argument specifiers you should know:

%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.<number of digits>f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

Strings in python have many properties which can easily transform the values as per user requirement. Some of the properties are:

  • name= "Python"
    variable.upper()
     #Python
  • name="Python String"
    variable.split()
    #["Python", "String"]
  • name= ["Python","Data","Science"]
    print(' ',join(name))
    #Python Data Science

    Some of others Properties are :

  • String.Strip() # can be used to remove the characters from beginning and end of a string
    
    String.replace() # it is used to replace the occurance of the first argument with second argument within the string
    
    String.find() #It returns the  index of the first occurance of the string passed as the argument

We will learn more about strings and other integer examples in our next module. We will learn with more examples and practical scenarios. There are many Data Science problems which resolved by these real time solutions. Keep learning and stay tuned with our next module with more live python examples.

 

LEAVE A COMMENT

Code Calibre