Python Data Types


In Python, data types are classifications that categorize and specify the type of data that a variable can hold.

Common Data Types

  • Numeric
    • int: Integer type (e.g., 5, -10)
    • float: Floating-point type (e.g., 3.14, -0.5)
  • Text
    • str: String type (e.g., “hello”, ‘Python’)
  • Boolean
    • bool: Boolean type (either True or False)
  • Sequence
    • list: Ordered, mutable sequence (e.g., [1, 2, 3])
    • tuple: Ordered, immutable sequence (e.g., (1, 2, 3))
    • range: Represents a range of values
  • Set
    • set: Unordered, mutable collection of unique elements
    • frozenset: unchangeable set
    • my_set = {1, 2, 3}
  • Mapping
    • dict: Dictionary, an unordered collection of key-value pairs
    • my_dict = {'key': 'value'}
  • None
    • none: Represents the absence of a value or a null value

Setting The Data Type

  • not required
  • may be valuable at times, though
variableName = str("This is a string")          
variableName = int(42)              
variableName = list(("192.168.1.100", "192.168.1.101", "192.168.1.102"))
variableName = tuple(("192.168.1.100", "192.168.1.101", "192.168.1.102"))
variableName = dict(routerName="Cisco5501", ip="10.200.30.254")
variableName = set(("192.168.1.100", "192.168.1.101", "192.168.1.102"))

Checking Data Types

  • isalpha()

Numbers

Converting Number Data Types

  • can convert between numeric data types using explicit conversion functions
    • int(x): Convert x to an integer
    • float(x): Convert x to a floating-point number
    • round(x, n): Round x to n decimal places. If n is omitted or is None, it returns the nearest integer
    • abs(x): Return the absolute value of x

Important

When converting from a floating-point number to an integer, the decimal is truncated NOT rounded.

Random Numbers

  • Python does not have a function to create a random number
    • but has a built-in module for this called random
# Import the random module and display a random number between 1 and 100
import random 
print(random.randrange(1, 101))

Strings

Multiline Strings

  • can create multiline strings with triple quotes """
serverIPAddresses = """Server IP Addresses are:
172.18.100.10,
172.18.100.11,
172.18.100.12,
172.18.100.13"""
print(serverIPAddresses)

String Operations

  • Concatenation (+): Combining two strings
  • Repetition (*): Repeating a string multiple times
  • Indexing ([]): Accessing individual characters by position
    • Note: the first position is 0, and not 1. Python can do this because strings are considered arrays in Python
full_greeting = greeting + ", " + language  # Concatenation
repeated_str = number_str * 3  # Repetition
first_char = language[0]  # Indexing

String Looping

  • can loop through the string characters using a for loop
for x in “string looping”:
    print(x)

Formatted Strings

  • Formatted strings (f-strings) allow embedding expressions inside string literals

A Python expression is a combination of operators and operands that produces a value or result after being interpreted by the Python interpreter.

name = "Alice"
age = 25
message = f"Hello, my name is {name} and I am {age} years old."

Escape Characters

  • Special characters preceded by a backslash (\) for specific purposes

Example

  • \n for a new line
  • \t for a tab
multiline_str = "This is a\nmultiline\nstring."
tabbed_str = "This is a\ttabbed\tstring."

String Methods

  • Python provides numerous built-in methods for string manipulation
  • e.g., len(), upper(), lower(), replace(), split().
length = len(language)  # Length of the string
uppercase_str = language.upper()  # Convert to uppercase
lowercase_str = language.lower()  # Convert to lowercase
new_str = language.replace('P', 'J')  # Replace characters
word_list = language.split('t')  # Split into a list

Check Character Types

  • built-in methods to check if a character is of a certain type
    • e.g., uppercase, lowercase, alphanumeric, numerica, alpha, etc.
  • returns True or False
isUpper = "hello".isupper() # Checks if each character in string is uppercase
isLower = "hello".islower() # Checks if each character in string is lowercase
# above 2 only check alphabet characters, not numbers
isAlphaNumeric = "hello".isalnum() # Checks if alphanumeric
isNumeric = "hello".isnumeric() # Checks if numeric only
isAlpha = "hello".isalpha() # Checks if alphabet only
 
# can add `not` in front to check if it is not these things

Checking Strings

  • can check to determine whether a specific character or phrase exists within the string with in
strText = "The Python language can be used in network automation tasks"
print("automation" in strText)
  • can also check if a word is not in a string with not in
    • print("error" not in strText)

String Slicing

String slicing in Python refers to the technique of extracting a portion of a string by specifying a range of indices.

  • syntax: string[start:stop:step]
    • start: The index from which the slicing begins (inclusive)
      • defaults to the beginning
    • stop: The index at which the slicing ends (exclusive)
      • defaults to the end
    • step (optional): The step or stride between characters
      • defaults to 1
text = "Hello, Python!"
# Extracting a substring from index 7 to the end
substring = text[7:]
print(substring)  # Output: "Python!"
 
# Extracting the first 5 characters
first_five = text[:5]
print(first_five)  # Output: "Hello"
 
# Extracting characters with a step of 2
every_second = text[::2]
print(every_second)  # Output: "Hlo yhn"
 
# Reversing a string
reversed_str = text[::-1]
print(reversed_str)  # Output: "!nohtyP ,olleH"

Modify Strings

  • strings are immutable
    • cannot be changed
  • to modify, need to create a new one with the changes
    • always assign to a new variable

String Length

The len() method returns the length (number of characters) of a string.

text = "Hello, Python!"
length = len(text)
print(length)  # Output: 14

Converting Characters

  • upper() method converts all characters in a string to uppercase
  • lower()method converts all characters in a string to lowercase
text = "Hello, Python!"
uppercase_text = text.upper()
lowercase_text = text.lower()
print(uppercase_text)  # Output: "HELLO, PYTHON!"
print(lowercase_text)  # Output: "hello, python!"
  • title() method converts the first character of each word to uppercase
text = "hello python programming"
title_text = text.title()
print(title_text)  # Output: "Hello Python Programming"
  • capitalize() method capitalizes the first character of a string
text = "hello, python!"
capitalized_text = text.capitalize()
print(capitalized_text)  # Output: "Hello, python!"

Counting Substrings

  • useful for parsing network data, such as logs or command outputs
    • helps in identifying recurring patterns, validating data, or detecting anomalies, thereby enhancing network monitoring and troubleshooting
  • count() method counts the occurrences of a substring in the given string
text = "python is powerful, python is easy"
count_python = text.count("python")
print(count_python)  # Output: 2

Replacing Substrings

  • replace() method replaces occurrences of a specified substring with another string
text = "Python is easy and Python is fun"
new_text = text.replace("Python", "Java")
print(new_text)
# Output: "Java is easy and Java is fun"

Removing Whitespace

  • strip(): method removes leading and trailing whitespaces
  • lstrip() method removes leading whitespaces
  • rstrip():  method removes trailing whitespaces
text = "   Python is easy   "
stripped_text = text.strip()
print(stripped_text)  # Output: "Python is easy"

Concatenate Strings

  • concatenate two strings with + operator
  • can concatenate strings with other data types
    • first convert to a string with str()
    • then use +
age = 25
message = "My name is " + first_name + " and I am " + str(age) + " years old."
print(message)
# Output: "My name is John and I am 25 years old."

+= Operator

  • += operator can be used as a shorthand for concatenation and assignment
greeting = "Hello, "
greeting += "Python!"
print(greeting)  # Output: "Hello, Python!"

Joining Strings

  • join() method is used to concatenate strings from an iterable (e.g., a list)
words = ["Python", "is", "awesome"]
sentence = " ".join(words)
print(sentence)  # Output: "Python is awesome"

Formatted Strings

The format() method in Python is a powerful and flexible way to format strings by replacing placeholders with values.

  • Use {} as placeholders for variables
  • pass variables into .format() method

Positional Arguments

Positional arguments are arguments that are passed to a function or method in a specific order.

name = "John"
age = 25
# Using format() method with placeholders
message = "My name is {} and I am {} years old.".format(name, age)
print(message)
# Output: "My name is John and I am 25 years old."

Named Arguments

Named arguments are arguments that are passed to a function or method by explicitly stating the name of the parameter and its value.

  • aka keyword arguments
  •  allows you to specify arguments in any order
# Named arguments in format()
details = "Name: {name}, Age: {age}".format(name="Alice", age=30)
print(details)
# Output: "Name: Alice, Age: 30"

Index-based Formatting

Index-based formatting is a feature of the str.format() method where you can specify the order in which values should be formatted.

  • place index numbers inside the curly braces {} that serve as placeholders in the original string
# Index-based formatting
message = "{0} is a {1} programming language.".format("Python", "versatile")
print(message)
# Output: "Python is a versatile programming language."

Number Formatting

In Python, number formatting is used to control how numbers are displayed.

  • useful for:
    • display numbers in a more readable format
    • or control the precision of floating point numbers
# Number formatting
value = 1234567.89
formatted_value = "Formatted Value: {:,.2f}".format(value)
print(formatted_value)
# Output: "Formatted Value: 1,234,567.89"

Padding and Alignment

In Python, padding and alignment are used to format strings for better readability and presentation.

Padding refers to adding characters to a string to reach a certain length.

  • used for output formatting and alignment
  • 3 types of padding:
    • Left Padding: Characters are added to the start of the string 
    • Right Padding: Characters are added to the end of the string
    • Center Padding: Characters are added to both ends of the string until it reaches a specified length

Alignment refers to the way text is positioned within a given space.

  • align strings using the format() method with alignment operators:
    • <: Forces the field to be left-aligned within the width
    • >: Forces the field to be right-aligned within the width
    • ^: Forces the field to be centered within the width

Example

# Padding and alignment
text = "Python"
formatted_text = "{:^10}".format(text)
print(formatted_text)
# Output: "  Python  "
  • ^ denotes center alignment with width of 10 characters

Booleans

In Python, the Boolean type (bool) represents a binary state, indicating either True or False.

  • Boolean values: True or False
  • Used with Logical operators:
    • and, or, not
  • Comparison operators return a boolean
    • ==, !=, <, >, <=, >=
  • Truth and Falsy values:
    • Truthy: non-zero numbers and non-empty strings
    • Falsy: zero, None, and empty strings are falsy
  • Convert other data types to boolean with bool() function
    • e.g., bool_num = bool(number) # True
  • fundamental for conditional statements such as if, else, and elif