Python How to Built in Functions Pt 4

PythonThere are numerous built in functions and library modules in Python. Definitely more than I can cover in one article, but I will go over many of them today.

I’ll specifically cover the most commonly used functions pertaining to mathematical operations and string manipulation. All also throw in some random issues that are sure to come up.

Numerical Operations in Python

Here are the common operations that I’m sure you know, and a few that require some explanation:

  • x + y : Addition
  • x – y : Subtraction
  • x * y : Multiplication
  • x / y : Division
  • x % y : Modulus – Returns the remainder of a division
  • x // y : Divides x by y and drops the fractional part
  • x ** y : Raises x to the power of y

Shorthand Numerical Operations

You know what “x = x + 1”, does. There is a shorthand way to perform this same operation and that is “x += 1”. You can in fact perform this shorthand with all of the numerical operators above.

You can’t however use the common shorthand “x++”, which is found in many other languages. Sorry.

Standard Python Mathematical Functions

These functions are available to use out of the box with Python:

  • abs(x) : Returns the absolute value of x
  • bin(x) : Returns the binary version of x
  • divmod(x, y) : Returns the division of x by y as a tuple with two integers
  • float(x) : Converts an integer into a float
  • hex(x) : Returns the hexadecimal version of x
  • int(x) : Converts a float into an integer
  • pow(x, y) : Raises x to the power of y
  • round(x, y) : Returns x rounded to y integral digits

Math Module Mathematical Functions

To access the multitude of math functions, commonly used in Python, just import the module math near the beginning of your code. Just type import math. That’s it. Here is some of what you’ll get:

  • math.ceil(x) : Returns the smallest integer greater than x
  • math.factorial(x) : Returns x!
  • math.floor(x) :  Returns the greatest integer less than or equal to x
  • math.isnan(x) : Returns True if x is not a number
  • math.pow(x, y) : Returns x to the power of y
  • math.sqrt(x) : Returns the square root of x
  • math.trunc(x) : Returns the integer form of float x

Also there are numerous logarithmic and trigonometric formulas.


String Escape Symbols

What do you do when you want to use a quote within a string surrounded by quotes? You use what are called String Escapes. A String Escape is started with a backslash, followed by normally the character to escape. So it would be legal to use this code:

print(“He said \”I love Python\””)

It would have been a better idea to use single quotes like this ‘He said “I love Python”‘, but believe me, that won’t always be an option. Here are some other escape strings:

  • \\ : Backslash
  • \” : Double Quote
  • \’  : Single Quote
  • \b : Back Space
  • \f : Form Feed
  • \n : Line Feed
  • \N{name} : Unicode Character with its Given Name
  • \r : Carriage Return
  • \t : Tab

Playing with String Methods

Python is fabulous at manipulating strings. Here I’ll show you, through example, just a few cool things you can do:

a = “A string of characters”
b = “and stuff”
c = “Another string {} {}”.format(b, a)

In the first 2 lines of code, I’m creating 2 strings. In the third, I’m creating a new string and I’m placing additional strings inside of the new one with the format function. The variables you want to insert, are designated by where you place the curly braces {}. They will be added in the order you wish.

Next to the print commands below, you can see the output in the comment.

print(a) # A string of characters
print(c) # Another string and stuff A string of characters

The find function will return the first instance of what ever string you ask for. So for example

print(a.find(‘of’)) # 9

Returns 9, as you see in the comment. This occurs because the word “of” starts in the 9th index of the a string. The replace function will replace the string ‘of’, with the string ‘and’, in the string named a below. You can see the output of this print function in the comment that follows it. Note that the string a itself wasn’t effected by the replace command.

print(a.replace(‘of’, ‘and’)) # A string and characters
print(a) # A string of characters

If we wanted to eliminate additional white space from the beginning of a string, we can with the strip function as you can see.

d = ‘  A string with extra white space  ‘.strip()
print(d) # A string with extra white space

I then show how you can break a string into pieces, with the split function. And, if I was to run the for loop below, the strings would be printed in order like this:


e = d.split()
print(e) # [‘A’, ‘string’, ‘with’, ‘extra’, ‘white’, ‘space’]
for f in e: print(f)

If you decided to join these strings with a comma and space between, you can with the join function.

g = ‘, ‘.join(e)
print(g) # A, string, with, extra, white, space

To see the length of the string, just use the len function as I show here:

h = len(g)
print(h) # 36

There are numerous string functions available with Python. I’ll touch on Regular Expressions in a later article as well, but here is a short run down on additional functions for string manipulation with Python.

More Python String Methods

  • capitalize() : Capitalizes the first letter of a string
  • center(width,fillchar) : Adds spacing to a string, based off of the designated fill char (Default fillchar : Space)
  • count(sub) : Counts the number of times the sub string appears
  • lower() : Converts every character in the string to lower case
  • lstrip(sub) : Removes the substring from the left side of the string or white space by default
  • rstript(sub) : Same as lstrip except with the right side
  • upper() : Converts every character in the string to upper case

There are many other methods available in the Python Documentation site. These should keep you pretty busy though.

That’s All Folks

Like I stated above, in the next article I’ll cover how to manipulate text with Regular Expressions using Python. If you have any questions, leave them below

Till Next Time

Think Tank

3 Responses to “Python How to Built in Functions Pt 4”

  1. Sumone says:

    Thanks a lot.

  2. Adil says:

    I believe you mentioned earlier that the Python modules have been completed, however, I would really really like for you to cover something about ‘Scrapy’

    The sessions in Lesson 13/14, albeit great, does not address about automatic login, especially with complicated sites such as .aspx which contains viewstates, etc.

    Would you consider this request and/or are there better alternatives that I can consider.

    Your input will be much appreciated.

    • admin says:

      Yes I completed the Python tutorials for now. That doesn’t mean I won’t get back into them though. I try to make complete tutorials that cover pretty much everything about a language. I cover languages even more completely now than I did back with Python.

      It is just extremely hard to bounce from one language tutorial to another. I’d forget what I covered and you the reader would be completely confused 🙂 I’ll do more with Python. I have no idea who else does tutorials on it, but I’m sure there must be many people? I don’t watch other peoples tutorials so that I’m not influenced by them.

Leave a Reply

Your email address will not be published.