Tuesday, July 31, 2018

(Python) Basic Data Manipulation

In the previous article, we discussed data types. In this entry we will review a few basic data manipulation techniques. To reiterate, I do understand that this subject matter is extremely foundational, and that is indeed the premise.

To assign a variable:

a = 15

b = 16


To print a variable:

print(a)

To multiply variables:

print(a * b)

To add variables:

print(a + b)

To subtract variables:

print(a - b)

To create an exponential value:

# Square the value of "a" #

print(a ** 2)


To produce a remainder value:

# This operator is also known as a "modulus" #

print(a % b)


To store the result of a calculation:

c = a + b

To join multiple strings:

a = "the dog"

b = "is"

c = "brown"

d = a + " " + b + " " + c

# The additional quotes create space between each string variable #

print(d)


Console Output:

the dog is brown

Assignment Trickery

Let us consider the following lines of code:

a = 5

b = a

a = 6


What would we expect to print to the console if we performed the following function?

print(b)

You might assume that the value that would be output pertaining to variable “b” would be:

6

However, this is not the case. Instead of the value “6”, the value “5” is printed to the console. The reason for such is that the value of “b” was assigned the value of variable “a” prior to the re-assignment. As is the case, "b" refers to the value of “a” at the time, not the variable itself in a dynamic sense.

If we wanted to correct this confusion, we could do so with the following code:

a = 5

b = a

a = 6

b = a

print(b)


Which would produce the following console output:

5

Fun with Strings

The following are a few useful functions which are especially useful when modifying string variables.

strip()

The strip function removes blank spaces from the beginning and end of a string variable value:

a = " Strip this string "

print(a.strip())


The console output is as follows:

Strip this string

len()

The length function provides the length of the string variable passed to the function.

a = "What’s going on?"

print(len(a))


The console output is as follows:

16

lower()

The lower function modifies the string variable to all lower case lettering.

a = "WHAT’S GOING ON?!"

print(a.lower())

The console output is as follows:

what’s going on?!

upper()

The upper function modifies the string variable to all upper case lettering.

a = "make this all upper case!"

print(a.upper())


The console output is as follows:

MAKE THIS ALL UPPER CASE!


split()

The split() function splits the string into a list containing each element as an aspect of the prior string.

a = "split, this, line up!"

print(a.split(",")) # The separator in this case is a comma (",") #


The console output is as follows:

['split', ' this', ' line up!']

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.