\

1
Python – Functions and strings

Hi guys, hope you all are catching along with previous Learn Python From Scratch tutorial, in this post you will come across python functions and string operations.

Functions are a construct to structure programs. They are known in most programming languages, sometimes also called subroutines or procedures. Functions are reusable piece of code that can be invoked as many times as required in the program and perform certain task.

In Python a function is some reusable code that takes arguments(s) as input, does some computation, and then returns a result or results. We define a function using the def reserved word. We call/invoke the function by using the function name, parentheses, and arguments in an expression 

There are two kinds of functions in python.

-  Built-in functions that are provided as part of Python library - print(), input(), type(), float(), int()
-  Functions that we define ourselves and then use

Building our own function:
  • We create a new function using the def keyword followed by optional parameters in parentheses
  • We indent the body of the function
  • This defines the function but does not execute the body of the function



Docstring: The first string after the function header is called the docstring and is short for documentation string. It is used to explain in brief, what a function does.
Although optional, documentation is a good programming practice. Unless you can remember what you had for dinner last week, always document your code.
In the above example, we have a docstring immediately below the function header. We generally use triple quotes so that docstring can extend up to multiple lines. This string is available to us as __doc__ attribute of the function. For example:

def greet(name):
            """This function greets to the person passed in as parameter"""
            print("Hello, " + name + ". Good morning!")

Try running the following script with the below addition:
print(greet.__doc__)

You will get the output on your console as,
>>> This function greets to the person passed into the name parameter

This is the end of the first topic of discussion in this post which was functions. Now let’s see what does "Strings" in python have to offer to a programmer.

A String,
  • contiguous series of characters delimited by single or double quotes
  • A string literal is initialised with values in quotes. 
  • Python don’t have any separate data type for characters, so they are represented as a single character string. 
  • Strings in python are immutable, i.e. that once string is created it can’t be modified. 
  • For strings, + operator means “concatenate”. 
  • When a string contains numbers, it is still a string but they can be converted into numbers int().


We can get at any single character in a string using an index specified in square brackets. The index value must be an integer and starts at zero. If you try to attempt to access using index beyond the length of the string python gives a traceback. The built-in function to check the length of the string is len(). The string operations offered by python are:


The method startswith() checks whether string starts with str, optionally restricting the matching with the given indices start and end. 

It has the following syntax:
str.startswith(str, beg=0,end=len(string));





The replace() function is like a “search and replace” operation in a word processor. It replaces all occurrences of the search string with the replacement string. 






1. We use the find() function to search for a substring within another string. 

2. find() finds the first occurrence of the substring. 

3. If the substring is not found, find() returns -1.


 Slicing a string is a powerful tool in python strings wherein we can extract some part of a string. Slicing is performed using colon operator. We extend the square-bracket syntax a little, so that we can specify not only the starting position of the piece we want, but also where it ends. If we leave off the first number or the last number of the slice, it is assumed to be the beginning or end of the string respectively.

You can use ( > , <, <= , <= , == , !=  ) to compare two strings.

Python compares string lexicographically i.e using ASCII value of the characters.





1. Sometimes we want to take a string and remove whitespace at the beginning and/or end.

2. lstrip() and rstrip() remove whitespace at the left or right.

3. strip() removes both beginning and ending whitespace.



Here are some of the most common string methods,
  1. s.lower(), s.upper() -- returns the lowercase or uppercase version of the string
  2. s.strip() -- returns a string with whitespace removed from the start and end
  3. s.isalpha(), s.isdigit(), s.isspace()... -- tests if all the string chars are in the various character classes
  4. s.startswith('other'), s.endswith('other') -- tests if the string starts or ends with the given other string
  5. s.find('other') -- searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found
  6. s.replace('old', 'new') -- returns a string where all occurrences of 'old' have been replaced by 'new'
  7. s.split('delimiter') -- returns a list of substrings separated by the given delimiter. The delimiter is not a regular expression, it's just text. 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. As a convenient special case s.split() (with no arguments) splits on all whitespace chars.
  8. s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. e.g. '---'.join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc
  9. s.replace(str1, str2) – this function is like search and replace operations where ot replaces all occurences of the search string str1 by the replacement string str2.
So here we are, at the end of the post, lets summarize the topics we have seen today. Functions: What are they? Why are they used? How can we define a function? Strings: What are they? How are they used and various methods that provide some meaningful operations perform-able to these string. This concludes the post, stay tuned for the next post on the topic of file operations, until then guys enjoy your time browsing through other posts in the blog!! Please leave your questions in the comments section if any. 
Next
This is the most recent post.
Previous
Older Post

Post a Comment

  1. During your study you will focus on four main areas: white collar crime, information risk management, cyber law and digital forensics. cyber security institute in hyderabad

    ReplyDelete

 
Top