Saturday, July 19, 2014

django - More about Python

In our previous post, we learned that we need not specifically declare a data type for any variable.  Python defines the data type based on the value assigned to that variable.

But, if you ever want to know the data type of a particular variable, you can use the 'type' function.

The following screen shows the different data types returned by Python based on the value.

 

Notice that, for different values, we get the data types as 'int', 'str', 'float', 'list' and 'bool'.  A word about 'bool' data type is that, it represents one of two values: 'True' or 'False'.  Note that this is case sensitive and so values like 'true' or 'false' will fail.

Now, the interesting thing about working with strings is that you can specify the range of values to retrieve.  Like 'substring' function in Java or C#.



Using ':' in the index will specify Python to retrieve the substring depending on what values are given.

>>> a[:5] # retrieves the first 5 characters.

>>> a[0:6] # retrieves the characters from position 0 thru 6.

>>> a[7:] # retrieves the characters from position 7 thru the end of the string.

As you remember, giving '-1' value as the index number will return the last character of the string value and working backwards to the first character.



Another interesting thing here is, you can specify another ':' in the index to skip the defined number of characters and return the remaining string.

For example:



So, entering 'a[::2]' will skip every second character in the string and returns the remaining string.

As the above screen shows, if we have variable 'a' containing "django is cool", we get back "'dag sco".

If you want to get the reverse value of the string, simply enter 'a[::-1]'.

The use of ':' is termed as slicing.  The pattern is as follows:

a[b:e:i]

Where 'a' is a list variable or an array.  'b' is the beginning position, 'e' is the ending position and 'i' is the interval.

There are many other useful functions in Python like 'help' and 'dir'.

'dir' returns the list of possible methods available for the given variable or an object.



Notice that, at first we have assigned a numeric value to the variable 'a'.  So when we do 'dir(a)', it returns the available properties and methods for this integer data type.  Likewise, when we assigned a string value and did 'dir(a)', it returns different set of properties and methods available, in this case, for the string data type.
 

Let's explore some of the string methods available.



The above screen shows the use of 'lower', 'upper', 'islower', 'isupper' and 'capitalize' methods.  The method names are self-explanatory.  'lower' method returns the lower case value of the string while 'upper' method returns the upper case.

Methods 'islower' and 'isupper' check whether the value is having all lower case or upper case and accordingly returns True or False.

'capitalize' method returns the string value with the first character as capital or upper case.

If we want to know the position of any character or substring within a string variable, we can use either 'find' or 'index' methods.  Both will return the integer value of the position where the first match of the character was found.

So, you may ask that if 'first' and 'index' methods work the same way, what is the difference here?  

The main difference is that, 'first' returns the value -1 if no match was found.  Where as, 'index' will return an error in that scenario.

Before we proceed with checking the examples, I want to mention another important feature 'help'.  If you want to know how a particular syntax works or how a particular method is used, you can enter 'help' and then enclose that method in parenthesis.

Below screen shows how 'help' can be used:

 

Now let us look at how to use these methods:

 

As you notice, both 'find' and 'index' will return the position of the first match of the given character, if it is found.  Else, 'find' returned -1 where as 'index' returned error.

You can specify additional values like 'start' and 'end' positions to search for the matching character.  

While 'find' and 'index' returns the first occurrence of the matching character, in order to find the last occurrence of the same, we can use 'rfind' and 'rindex' accordingly.  The 'r' here denotes right-most match.



The above screen shows how different values are returned when using 'find' and 'rfind' and similarly when using 'index' and 'rindex'.

If you are not bothered about the position where the match was found but just want to check whether a particular character or string is present within a main string, you can use 'in' statement.

 

If a matching character or string is found, 'True' is returned'  Else, 'False' is returned.

To get the list of words from a string variable, you can use the 'split' function.  This takes a white space or blank character as a kind of delimiter (or separator) by default and returns all the words in a given sentence in the form of a list.

 

Note that after we give the 'split' command, we get 3 different words present in the string variable 'a'.

You can choose to specify any character to act as a separator for the 'split' function.  Python returns the set of words accordingly as shown below where we used the comma (,) as the separator:



Note that it returns the list of words along with the leading spaces in each word.

We have a 'replace' function to replace a set of characters or words with another set.  By default, this function replaces all the occurrences of a old character/ word with the new one.  But, you can choose to specify the count for the number of places to replace.



Observe in the above example that in the first instance of using 'replace' function, when we did not specify the count, it replaced all the occurrences of 'o' with 'a'.  But, in the second instance when we specify the count of 2, it replaced only in the first two matching occurrences of 'o' and did not replace the last one.

Moving on further, we have a function 'swapcase' as the name suggests that will switch and return the case of the characters present in the string.  I mean, it converts all the upper case ones to lower case and vice versa.

 

If we have a string value which has leading and/ or trailing spaces and want to get the trimmed off value, we can use the 'strip' function which will remove the extra spaces.



And we have a function 'title' which will convert the first character of the word in the string value and returns it.

 

Earlier, we have found what 'split' function does.  It basically returns the set of words or characters based on the given separator or delimiter.  What if you want to combine or join them again?

This can be done using the 'join' function.   It concatenates the set of words into a single string.



Some more in the next post.

No comments:

Post a Comment