python

exercises

exercises.pyšŸ
"""
02 - Strings: Exercises
Practice string manipulation!
"""

print("=" * 60)
print("STRINGS - EXERCISES")
print("=" * 60)

# =============================================================================
# EXERCISE 1: String Basics
# =============================================================================
print("\n--- Exercise 1: String Basics ---")

# Given string:
text = "Python Programming"

# TODO: Find and print:
# a) The length of the string
# b) The first character
# c) The last character
# d) The 7th character (index 6)

# Your code here:
length = None
first_char = None
last_char = None
seventh_char = None

# =============================================================================
# EXERCISE 2: String Slicing
# =============================================================================
print("\n--- Exercise 2: String Slicing ---")

# Given string:
text = "Hello, World!"

# TODO: Extract:
# a) "Hello"
# b) "World"
# c) Every other character (starting from first)
# d) The string reversed

# Your code here:
hello = None
world = None
every_other = None
reversed_text = None

# =============================================================================
# EXERCISE 3: String Methods
# =============================================================================
print("\n--- Exercise 3: String Methods ---")

# Given string:
text = "  PyThOn PrOgRaMmInG  "

# TODO: Create these versions:
# a) Stripped and lowercase
# b) Stripped and uppercase
# c) Stripped and title case
# d) With all 'o' replaced with '0' (zero)

# Your code here:
lowercase = None
uppercase = None
titlecase = None
replaced = None

# =============================================================================
# EXERCISE 4: Split and Join
# =============================================================================
print("\n--- Exercise 4: Split and Join ---")

# Given:
csv_data = "apple,banana,cherry,date,elderberry"

# TODO:
# a) Split into a list of fruits
# b) Join the fruits with " - "
# c) Join the fruits with " and "

# Your code here:
fruits_list = None
joined_dash = None
joined_and = None

# =============================================================================
# EXERCISE 5: String Formatting
# =============================================================================
print("\n--- Exercise 5: String Formatting ---")

# Given data:
product = "Laptop"
price = 999.99
quantity = 3

# TODO: Create these formatted strings using f-strings:
# a) "Product: Laptop"
# b) "Price: $999.99"
# c) "Total: $2999.97" (price * quantity, 2 decimal places)
# d) "Laptop.......999.99" (product left-aligned, price right-aligned, width 20)

# Your code here:
output_a = None
output_b = None
output_c = None
output_d = None

# =============================================================================
# EXERCISE 6: String Validation
# =============================================================================
print("\n--- Exercise 6: String Validation ---")

# Check each string and set the appropriate boolean:
test1 = "HelloWorld"
test2 = "12345"
test3 = "Hello123"
test4 = "   "
test5 = "ALLCAPS"

# TODO: Check if each string matches the condition:
is_alpha = None     # test1 is all letters?
is_digit = None     # test2 is all digits?
is_alnum = None     # test3 is alphanumeric?
is_space = None     # test4 is all whitespace?
is_upper = None     # test5 is all uppercase?

# =============================================================================
# EXERCISE 7: Count and Find
# =============================================================================
print("\n--- Exercise 7: Count and Find ---")

# Given:
text = "The quick brown fox jumps over the lazy dog"

# TODO:
# a) Count how many times 'the' appears (case insensitive)
# b) Find the index of 'fox'
# c) Find the index of 'cat' (should be -1)
# d) Check if the text contains 'quick'

# Your code here:
the_count = None
fox_index = None
cat_index = None
has_quick = None

# =============================================================================
# EXERCISE 8: Password Validator
# =============================================================================
print("\n--- Exercise 8: Password Validator ---")

# Given password:
password = "MyP@ssw0rd123"

# TODO: Check if password meets ALL these criteria:
# - At least 8 characters long
# - Contains at least one uppercase letter
# - Contains at least one lowercase letter
# - Contains at least one digit

# Your code here:
is_long_enough = None
has_upper = None
has_lower = None
has_digit = None
is_valid = None  # True if ALL criteria are met

# =============================================================================
# EXERCISE 9: Text Statistics
# =============================================================================
print("\n--- Exercise 9: Text Statistics ---")

# Given:
paragraph = "Python is a versatile programming language. Python is used for web development, data science, and automation. Python is easy to learn."

# TODO: Calculate:
# a) Number of words
# b) Number of sentences (hint: count periods)
# c) Number of times "Python" appears
# d) Number of characters (excluding spaces)

# Your code here:
word_count = None
sentence_count = None
python_count = None
char_count_no_spaces = None

# =============================================================================
# EXERCISE 10: String Transformation
# =============================================================================
print("\n--- Exercise 10: String Transformation ---")

# TODO: Implement these functions:

def reverse_words(sentence):
    """Reverse the order of words in a sentence.
    Example: "Hello World" -> "World Hello"
    """
    # Your code here:
    return None

def remove_vowels(text):
    """Remove all vowels from text.
    Example: "Hello" -> "Hll"
    """
    # Your code here:
    return None

def is_palindrome(text):
    """Check if text is a palindrome (ignoring case and spaces).
    Example: "Race Car" -> True
    """
    # Your code here:
    return None

def count_vowels(text):
    """Count number of vowels in text.
    Example: "Hello" -> 2
    """
    # Your code here:
    return None

# Test your functions:
# print(reverse_words("Hello World Python"))  # Python World Hello
# print(remove_vowels("Hello World"))  # Hll Wrld
# print(is_palindrome("Race Car"))  # True
# print(count_vowels("Hello World"))  # 3

# =============================================================================
# SOLUTIONS
# =============================================================================
print("\n" + "=" * 60)
print("SOLUTIONS (scroll down after trying!)")
print("=" * 60)

"""
EXERCISE 1:
length = len(text)           # 18
first_char = text[0]         # 'P'
last_char = text[-1]         # 'g'
seventh_char = text[6]       # ' '

EXERCISE 2:
hello = text[0:5]            # 'Hello'
world = text[7:12]           # 'World'
every_other = text[::2]      # 'Hlo ol!'
reversed_text = text[::-1]   # '!dlroW ,olleH'

EXERCISE 3:
lowercase = text.strip().lower()           # 'python programming'
uppercase = text.strip().upper()           # 'PYTHON PROGRAMMING'
titlecase = text.strip().title()           # 'Python Programming'
replaced = text.strip().replace('o', '0').replace('O', '0')  # 'PyTh0n Pr0gRaMmInG'

EXERCISE 4:
fruits_list = csv_data.split(',')              # ['apple', 'banana', ...]
joined_dash = ' - '.join(fruits_list)          # 'apple - banana - ...'
joined_and = ' and '.join(fruits_list)         # 'apple and banana and ...'

EXERCISE 5:
output_a = f"Product: {product}"
output_b = f"Price: ${price:.2f}"
output_c = f"Total: ${price * quantity:.2f}"
output_d = f"{product:<10}{'.'*10}{price:>10.2f}"

EXERCISE 6:
is_alpha = test1.isalpha()   # True
is_digit = test2.isdigit()   # True
is_alnum = test3.isalnum()   # True
is_space = test4.isspace()   # True
is_upper = test5.isupper()   # True

EXERCISE 7:
the_count = text.lower().count('the')   # 2
fox_index = text.find('fox')             # 16
cat_index = text.find('cat')             # -1
has_quick = 'quick' in text              # True

EXERCISE 8:
is_long_enough = len(password) >= 8
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)
is_valid = is_long_enough and has_upper and has_lower and has_digit

EXERCISE 9:
word_count = len(paragraph.split())                    # 27
sentence_count = paragraph.count('.')                  # 3
python_count = paragraph.count('Python')               # 3
char_count_no_spaces = len(paragraph.replace(' ', '')) # 113

EXERCISE 10:
def reverse_words(sentence):
    return ' '.join(sentence.split()[::-1])

def remove_vowels(text):
    vowels = 'aeiouAEIOU'
    return ''.join(c for c in text if c not in vowels)

def is_palindrome(text):
    cleaned = text.lower().replace(' ', '')
    return cleaned == cleaned[::-1]

def count_vowels(text):
    vowels = 'aeiouAEIOU'
    return sum(1 for c in text if c in vowels)
"""

print("\nšŸŽ‰ Great job! Move on to 03_control_flow when ready!")
Exercises - Python Tutorial | DeepML