Basic String Operations

In this class, we will delve into basic operations with strings, which are manipulations that can be performed on strings to modify them or extract information from them.

Basic operations Link to heading

  • len(string): Gets the length of the string (number of characters).
  • string.upper(): Converts the string to uppercase.
  • string.lower(): Converts the string to lowercase.
  • string.count(substring): Counts the number of occurrences of a substring in the string.
  • string.swapcase(): Reverses the case of the string.
  • string.startswith(prefix): Checks if the string starts with a specific prefix.
  • string.endswith(suffix): Checks if the string ends with a specific suffix.
  • string.replace(substring, new_substring): Replaces all occurrences of one substring with another.

Example Link to heading

string = "Hello world!"

# Get the length of the string
length = len(string)

# Convert the string to uppercase
string_upper = string.upper()

# Convert the string to lowercase
lowercase_string = string.lower()

# Count the number of occurrences of the letter "o"
number_o = string.count("o")

# Reverse the case of the string
swapcase_string = string.swapcase()

# Check if the string starts with "Hello"
starts_with_hello = string.startswith("Hello")

# Check if the string ends with "!"
ends_with_exclamation = string.endswith("!")

# Replace "world" with "universe"
replaced_string = string.replace("world", "universe")

print(
length,
string_upper,
lowercase_string,
number_o,
swapcase_string,
starts_with_hello,
ends_with_exclamation,
replaced_string
)

Exit: Link to heading

12 HELLO WORLD! hello World! 2 hElLo WoRlD! True True Hello universe!

More advanced operations Link to heading

  • string.split(separator): Splits the string into a list of substrings using a separator as a reference.
  • string.join(substring_list): Joins a list of substrings into a single string using a separator as a reference.
  • string.find(substring): Finds the first occurrence of a substring in the string and returns its index.
  • string.rfind(substring): Finds the last occurrence of a substring in the string and returns its index.

Example Link to heading

string = "Hello, world!"

# Split the string into a list of substrings
substring_list = string.split(",")

# Join a list of substrings into a single string
joined_string = ", ".join(substring_list)

# Find the first occurrence of the letter "o"
index_o = string.find("o")

# Find the last occurrence of the letter "o"
index_last_o = string.rfind("o")

print(
substring_list,
joined_string,
index_o,
index_last_o
)

Exit: Link to heading

['Hello', 'world!'] Hello, world! 4 7

Exercises Link to heading

Write Python code that counts the length of two strings, compares them, and determines if they are equal, ignoring case.

Keep experimenting with these string operations, perform different test cases to make sure your code works.

<< String Formatting Conditionals >>