Exercise: String Operations

Exercise 1: Convert to Uppercase

Task: Change a given string to uppercase.

Instructions:

  • Define a variable called text and assign it a string value (e.g., “natural language processing”).
  • Use the .upper() method to convert the string to uppercase.
  • Print the result.
Show solution
text = "natural language processing"

# Convert the string to uppercase
uppercase_text = text.upper()

# Print the result
print(uppercase_text)  # Output: NATURAL LANGUAGE PROCESSING
NATURAL LANGUAGE PROCESSING

Exercise 2: Count Vowels

Task: Count the number of vowels in a given string.

Instructions:

  • Define a variable called sentence and assign it a string value (e.g., “I love Python programming”).
  • Create a variable called vowel_count to keep track of the number of vowels in the sentence.
  • Loop through each character in the sentence and check if it is a vowel (a, e, i, o, u).
  • Print the total number of vowels.
Show solution
sentence = "I love Python programming"

# Initialize the vowel count
vowel_count = 0

# Define the set of vowels
vowels = "aeiouAEIOU"

# Loop through each character in the sentence
for char in sentence:
    if char in vowels:
        vowel_count += 1

# Print the total number of vowels
print("Number of vowels:", vowel_count)  # Output: Number of vowels: 8
Number of vowels: 7

Exercise 3: Replace a Word

Task: Replace a word in a string with another word.

Instructions:

  • Define a variable called text and assign it a string value (e.g., “NLP is fun”).
  • Use the .replace() method to change the word “fun” to “awesome”.
  • Print the modified string.
Show solution
text = "NLP is fun"

# Replace the word "fun" with "awesome"
modified_text = text.replace("fun", "awesome")

# Print the modified string
print(modified_text)  # Output: NLP is awesome
NLP is awesome

Exercise 4: Extract Substring

Task: Extract a substring from a given string.

Instructions:

  • Define a variable called text and assign it a string value (e.g., “Natural Language Processing”).
  • Use slicing to extract the word “Language” from the string.
  • Print the extracted substring.
Show solution
text = "Natural Language Processing"

# Extract the substring "Language" using slicing
substring = text[8:16]  # The indices may vary based on the string

# Print the extracted substring
print(substring)  # Output: Language
Language
Back to top