Python Strings : String Exercises

Here are some Python string exercises to help you practice and strengthen your understanding of string operations and methods:

Exercise 1: Reverse a String

Write a function that takes a string and returns the string reversed.

def reverse_string(s):
    return s[::-1]

# Test
print(reverse_string("hello"))  # Output: "olleh"

Exercise 2: Check Palindrome

Write a function to check if a given string is a palindrome (a word that reads the same forward and backward).

def is_palindrome(s):
    s = s.lower()  # Ignore case
    return s == s[::-1]

# Test
print(is_palindrome("racecar"))  # Output: True
print(is_palindrome("hello"))    # Output: False

Exercise 3: Count Vowels in a String

Write a function that counts the number of vowels (a, e, i, o, u) in a given string.

def count_vowels(s):
    vowels = "aeiouAEIOU"
    return sum(1 for char in s if char in vowels)

# Test
print(count_vowels("hello world"))  # Output: 3

Exercise 4: Find the First Non-Repeating Character

Write a function that finds the first non-repeating character in a given string.

def first_non_repeating(s):
    for char in s:
        if s.count(char) == 1:
            return char
    return None

# Test
print(first_non_repeating("hello world"))  # Output: "h"
print(first_non_repeating("aabbcc"))       # Output: None

Exercise 5: Remove All Whitespaces

Write a function to remove all whitespace characters from a string.

def remove_whitespaces(s):
    return s.replace(" ", "")

# Test
print(remove_whitespaces("hello world"))  # Output: "helloworld"

Exercise 6: Check if Two Strings are Anagrams

Write a function to check if two strings are anagrams (contain the same characters in a different order).

def are_anagrams(s1, s2):
    return sorted(s1) == sorted(s2)

# Test
print(are_anagrams("listen", "silent"))  # Output: True
print(are_anagrams("hello", "world"))    # Output: False

Exercise 7: Count Words in a String

Write a function to count the number of words in a string.

def count_words(s):
    return len(s.split())

# Test
print(count_words("hello world python"))  # Output: 3

Exercise 8: Replace Vowels with a Specific Character

Write a function that replaces all vowels in a string with a specified character.

def replace_vowels(s, replacement_char):
    vowels = "aeiouAEIOU"
    for vowel in vowels:
        s = s.replace(vowel, replacement_char)
    return s

# Test
print(replace_vowels("hello world", "*"))  # Output: "h*ll* w*rld"

Exercise 9: Find All Substrings

Write a function to find all possible substrings of a given string.

def all_substrings(s):
    substrings = []
    for i in range(len(s)):
        for j in range(i + 1, len(s) + 1):
            substrings.append(s[i:j])
    return substrings

# Test
print(all_substrings("abc"))  # Output: ['a', 'ab', 'abc', 'b', 'bc', 'c']

Exercise 10: Check if String is a Valid Password

Write a function that checks if a string is a valid password. A valid password must:

  • Be at least 8 characters long
  • Contain at least one uppercase letter
  • Contain at least one lowercase letter
  • Contain at least one digit
def is_valid_password(password):
    if len(password) < 8:
        return False
    has_upper = any(char.isupper() for char in password)
    has_lower = any(char.islower() for char in password)
    has_digit = any(char.isdigit() for char in password)
    return has_upper and has_lower and has_digit

# Test
print(is_valid_password("Hello123"))  # Output: True
print(is_valid_password("hello"))     # Output: False

Exercise 11: Count Occurrences of a Substring

Write a function to count the number of occurrences of a substring in a given string.

def count_substring(s, substring):
    return s.count(substring)

# Test
print(count_substring("hello hello world", "hello"))  # Output: 2

Exercise 12: Convert a String to Title Case

Write a function that converts a string to title case, where the first letter of each word is capitalized.

def to_title_case(s):
    return s.title()

# Test
print(to_title_case("hello world python"))  # Output: "Hello World Python"

Exercise 13: Check if a String Contains Only Digits

Write a function to check if a string contains only digits.

def is_only_digits(s):
    return s.isdigit()

# Test
print(is_only_digits("12345"))  # Output: True
print(is_only_digits("123a5"))  # Output: False

Exercise 14: Find the Longest Word in a String

Write a function that finds the longest word in a string.

def longest_word(s):
    words = s.split()
    return max(words, key=len)

# Test
print(longest_word("hello world python programming"))  # Output: "programming"

Exercise 15: Remove Duplicates from a String

Write a function to remove all duplicate characters from a string.

def remove_duplicates(s):
    return ''.join(sorted(set(s), key=s.index))

# Test
print(remove_duplicates("hello world"))  # Output: "helo wrd"

Conclusion:

These exercises cover a wide range of string manipulation techniques and help you build a deeper understanding of Python’s string methods and features. You can adjust the difficulty of the tasks by adding conditions or modifying the constraints.

Leave a Reply 0

Your email address will not be published. Required fields are marked *