Python quicky

Posted on August 15, 2016 in misc

A simple introduction to python:

Python is simple, fast and most importantly easy to learn language. Though I am not an expert at languages a good programming language should not make you worry or think about the implementation over logic.

The best way to get introduced to python is to start using it :

Variables in python:

Variables are lables that store a value which you have assigned to them. You can store strings or numbers. In python you can easily initialize variables ( numbers and strings) as shown below:

In [152]:
# consider two variables a, b
a =  1
b =  "I love programming"

# playing with numbers
print a * 5
# printing the strindg
print b
5
I am no
In [153]:
# In above example a * 5 gvies the value of 5, but to remember this value we have to store:
c = a * 5
print c
5

Printing to standard output :

You can simply print the values in variables to standard output using the "print" statement as shown below:

In [154]:
print b, a 
I am no 1
In [168]:
# print can be also used to output strings , not just variables:
print "life is good", "also great!", b, a 
life is good also great! I am no 1

Python Strings

  1. Python has a built in str class which offer various functionality .
  2. Strings are immutable.
  3. Strings are declared either betweet doeble quotes ("") or single quotes ('')

Python String functions :

Strings are the most commonly used data types in python. Strings come with some magical (nothing really magical) predefined functions that help us to play with them easily.

And we will be using python string functions in the later part of this tutorial as well.Hence lets explore these magical functions that make our life easy:

Lets consider an example string "Life is good" and store is this in a variable:

In [156]:
# Example String assigned to variable s:
s = "life is GREAT."

lower

This function Return's a copy of the string converted to lowercase.

In [157]:
print s.lower()
life is great.

upper

Similary the upper function returns a copy of the string converted to upercase.

In [158]:
print s.upper()
LIFE IS GREAT.

capitalize

Return's a copy of the string with only its first character changed to Capital.

In [159]:
print s.capitalize()
Life is great.

count

This function helps you to count the occurances of a substring within another string. In the below example we are counting the occurances of sub string "life" in the string s

In [160]:
print s.count("life")
print s.count("file")
print s.count("i")
1
0
2

split

The split function helps you split the string into sequence of words. It takes a delimmeter, based on which it splits the string into substrings. The defualt delimmiter is space.

If you have a sentence with words and want to extract each word in it , then split function can be used with sapce as an input delimmeter (which is default and need not be given as arguments). In the below example you can see that the output is a an list of substrings that the sentence is devided into.

In [161]:
print s.split()
print s.split("i")
['life', 'is', 'GREAT.']
['l', 'fe ', 's GREAT.']

strip

Strip is used to remove leading and trailing white spaces. If you just want to remove the leading spaces of a string then use the lstrip or if you just want to remove the trailing spaces use the rstrip. If characters are given as arguments, then strip removes the characters instead of spaces. The below examples show this clearly:

In [162]:
print s.strip()      # As no spaces in the original string , there is nothing to strip
print s.strip('l.')  # This removes the '.' and 'l' if it occurs either at beginning or end of the sentence.
life is GREAT.
ife is GREAT

join

Join works in a special way. Imagine you have list of words ['hello', "there!", "this", "is", "list"] and you want to join these induvidual words to form the sentence hello there! this is list. Obviously we want join them by spaces. We want to insert spaces between each of these induviaul words and form a string. Python gives us the maigc function to do this, which is the join. It takes an input list of words as shown below: Notice the quotes ' ' with space in between them in the below example. This is the character which we want to insert between the list of words that is passed as arguements.

In [163]:
# Notice the character between the quotes '_' or ' '.
print ' '.join(['hello', "there!", "this", "is", "list"])
print '_'.join(["hello", "there!", "this", "is", "list"])

# if no character is given: it would join the words in list without spaces
print ''.join(['hello', "there!", "this", "is", "list"])
hello there! this is list
hello_there!_this_is_list
hellothere!thisislist

NOTICE: Split and join do the opposite. And they are often used

In [164]:
# join
example = ' '.join(['hello', "there!", "this", "is", "list"])     
print example 

# split
print example.split() 
hello there! this is list
['hello', 'there!', 'this', 'is', 'list']

index

In [165]:
# index gives the position of a substring (this is given as argument) within a string
print "string s: ", s
print "position of substring 'is':", s.index('is')
string s:  life is GREAT.
position of substring 'is': 5

replace

In [166]:
# replace removes all the occurances of a substring and replaces with a given characters.
# s.replace(old, new)
s.replace("is", "is always")
Out[166]:
'life is always GREAT.'