Python – String Exercises

Welcome to The Coding College, your go-to platform for learning Python programming. Strings are one of the most fundamental aspects of Python, and practicing them is key to mastering the language. In this post, we’ve curated a variety of Python string exercises ranging from beginner to advanced levels.

These exercises are designed to help you solidify your understanding of Python string manipulation and string methods. Let’s dive in!

Why Practice String Exercises?

Strings play a crucial role in programming as they are used to handle and manipulate text. By solving string-related exercises, you’ll:

  • Gain a deeper understanding of string methods.
  • Learn how to handle real-world text processing tasks.
  • Improve problem-solving and logical thinking skills.

Beginner-Level Exercises

1. Length of a String

Write a program to calculate the length of a string entered by the user.

# Input: "Python"  
# Output: 6  

user_input = input("Enter a string: ")  
print(f"The length of the string is {len(user_input)}.")  

2. String Reversal

Reverse the given string without using slicing.

# Input: "Hello"  
# Output: "olleH"  

string = "Hello"  
reversed_string = ""  
for char in string:  
    reversed_string = char + reversed_string  
print(reversed_string)  

3. Count Vowels in a String

Count the number of vowels in a user-provided string.

# Input: "Education"  
# Output: 5  

vowels = "aeiouAEIOU"  
user_input = input("Enter a string: ")  
count = sum(1 for char in user_input if char in vowels)  
print(f"Number of vowels: {count}")  

Intermediate-Level Exercises

4. Check Palindrome

Check if a given string is a palindrome (reads the same backward as forward).

# Input: "madam"  
# Output: True  

string = input("Enter a string: ")  
is_palindrome = string == string[::-1]  
print(f"Is the string a palindrome? {is_palindrome}")  

5. Remove Spaces

Remove all spaces from a given string.

# Input: "Python Programming"  
# Output: "PythonProgramming"  

string = "Python Programming"  
result = string.replace(" ", "")  
print(result)  

6. Find Most Frequent Character

Find the character that appears the most in a given string.

# Input: "programming"  
# Output: "g"  

from collections import Counter  
string = "programming"  
most_common = Counter(string).most_common(1)[0][0]  
print(f"Most frequent character: {most_common}")  

Advanced-Level Exercises

7. Extract Numbers from a String

Extract all numbers from a string and return them as a list.

# Input: "My age is 25 and my brother's age is 20."  
# Output: [25, 20]  

import re  
string = "My age is 25 and my brother's age is 20."  
numbers = re.findall(r'\d+', string)  
print([int(num) for num in numbers])  

8. String Compression

Implement basic string compression using the counts of repeated characters.

# Input: "aaabbcc"  
# Output: "a3b2c2"  

def compress_string(s):  
    compressed = []  
    count = 1  
    for i in range(1, len(s)):  
        if s[i] == s[i - 1]:  
            count += 1  
        else:  
            compressed.append(s[i - 1] + str(count))  
            count = 1  
    compressed.append(s[-1] + str(count))  
    return ''.join(compressed)  

print(compress_string("aaabbcc"))  

9. Anagram Checker

Check if two strings are anagrams of each other.

# Input: "listen", "silent"  
# Output: True  

def are_anagrams(str1, str2):  
    return sorted(str1) == sorted(str2)  

print(are_anagrams("listen", "silent"))  

10. Longest Word in a Sentence

Find the longest word in a given sentence.

# Input: "The quick brown fox jumps over the lazy dog"  
# Output: "jumps"  

sentence = "The quick brown fox jumps over the lazy dog"  
words = sentence.split()  
longest_word = max(words, key=len)  
print(f"Longest word: {longest_word}")  

How to Use These Exercises

  1. Start Simple: Begin with the beginner-level problems to build confidence.
  2. Understand the Logic: Focus on why the solution works rather than just memorizing it.
  3. Experiment: Modify the problems to create your own variations.
  4. Practice Regularly: Revisit these exercises periodically to reinforce your skills.

Learn Python at The Coding College

At The Coding College, we’re committed to helping you excel in Python programming through hands-on exercises and practical tutorials.

Keep practicing and exploring, and don’t forget to check out our other Python tutorials for more learning opportunities.

Conclusion

Practicing string exercises is a great way to strengthen your Python programming skills. These exercises cover a wide range of string manipulation techniques that are not only helpful in interviews but also essential in real-world projects.

Leave a Comment