As you know, strings are widely used to store textual data. To perform programming tasks in Python, a good understanding of string manipulation is essential.
This article provides 35+ Python String practice questions that focus entirely on string operations, manipulation, slicing, and string functions.
Each coding challenge includes a Practice Problem, Hint, Solution code, and detailed Explanation, ensuring you don’t just copy code, but genuinely practice and understand how and why it works.
- All solutions have been fully tested on Python 3.
- Interactive Learning: Use our Online Code Editor to solve these exercises in real time.
Also Read:
- Python String Quiz: MCQs to help you get familiar with Python Strings
- Python String Interview Questions
Let us know if you have any alternative solutions. It will help other developers.
+ Table of Contents (38 Exercises)
Table of contents
- Exercise 1. Create a string made of the first, middle, and last character
- Exercise 2. Create a string made of the middle three characters
- Exercise 3. Append new string in the middle of a given string
- Exercise 4. Create a new string made of the first, middle, and last characters of each input string
- Exercise 5. Reverse a given string
- Exercise 6. Find the last position of a given substring
- Exercise 7. Split a string on hyphens
- Exercise 8. Find all occurrences of a substring in a given string by ignoring the case
- Exercise 9. String characters balance test
- Exercise 10. Vowel Counter
- Exercise 11. Prefix/Suffix Check
- Exercise 12. Swap Case
- Exercise 13. Remove Whitespace
- Exercise 14. N-th Character Removal
- Exercise 15. String Partitioning
- Exercise 16. Extract File Extension
- Exercise 17. Lowercase First
- Exercise 18. Count all letters, digits, and special symbols from a given string
- Exercise 19. Create a mixed string using alternating characters
- Exercise 20. Calculate the sum and average of the digits present in a string
- Exercise 21. Count occurrences of all characters within a string
- Exercise 22. Remove empty strings from a list of strings
- Exercise 23. Remove special symbols/punctuation from a string
- Exercise 24. Remove all characters from a string except integers
- Exercise 25. Find words with both letters and numbers
- Exercise 26. Replace each special symbol with # in the following string
- Exercise 27. Palindrome Check
- Exercise 28. Anagram Detector
- Exercise 29. Unique Character Check
- Exercise 30. Title Case Logic
- Exercise 31. Remove Duplicate Characters
- Exercise 32. Word Reversal
- Exercise 33. Character Interleaving
- Exercise 34. Longest Word
- Exercise 35. Acronym Creator
- Exercise 36. Word Frequency
- Exercise 37. First Non-Repeating Character
- Exercise 38. String Rotation Check
Exercise 1. Create a string made of the first, middle, and last character
Practice Problem: Write a program to create a new string made of an input string’s first, middle, and last characters.
Exercise Purpose: This exercise teaches the fundamentals of String Indexing. Accessing specific positions, especially the middle that requires calculating length, is a foundational skill for data parsing and text manipulation.
Given Input: str1 = "James"
Expected Output: Jms
Hint
- Use
str1[0]for the first character andstr1[-1]for the last. - To find the middle index, divide the length of the string by 2 using integer division (
//).
Solution
Explanation to Solution:
len(str1): This function calculates the total number of characters in the string.int(res / 2): Since indices must be integers, we divide the length to find the center point. For “James” (length 5), 5/2 is 2.5, which truncates to index 2 (the character ‘m’).str1[-1]: Python allows negative indexing.-1is a convenient shorthand to grab the very last character regardless of how long the string is.
Exercise 2. Create a string made of the middle three characters
Practice Problem: Write a program to create a new string made of the middle three characters of an input string of odd length.
Exercise Purpose: This builds on indexing by introducing String Slicing. Slicing is a powerful Python feature that lets you extract entire “chunks” of data efficiently.
Given Input: str1 = "JhonDipPeta"
Expected Output: Dip
Hint
- First, find the middle index.
- Then, slice the string from
middle - 1tomiddle + 2. - Remember that the ending index in a slice is exclusive.
Solution
Explanation to Solution:
mi = int(len(str1) / 2): Finds the center point of the string.str1[mi - 1 : mi + 2]: The syntax[start:end]extracts characters. We go one step back from the middle (mi-1) and two steps forward (mi+2).- Exclusive Range: In Python slicing, the
endindex is not included in the result. Therefore,mi + 2ensure that the character atmi + 1is the last one captured.
Exercise 3. Append new string in the middle of a given string
Practice Problem: Given two strings, s1 and s2, create a new string by appending s2 in the middle of s1.
Exercise Purpose: This exercise introduces String Partitioning and Concatenation. In programming, you often need to “inject” data into a template or modify strings at specific locations.
Given Input: s1 = "Ault" s2 = "Kelly"
Expected Output: AuKellylt
Hint
- Find the middle of
s1usinglen(s1) // 2. - Split
s1into two halves using slicing, then join them back together withs2in between using the+operator.
Solution
Explanation to Solution:
s1[:mi]: This slice captures everything from the start-up to the middle index.s1[mi:]: This slice captures everything from the middle index to the very end.x + s2 + y: Python uses the plus operator to “glue” strings together. By placings2between the two halves ofs1, we effectively insert it into the center.
Exercise 4. Create a new string made of the first, middle, and last characters of each input string
Practice Problem: Given two strings, s1 and s2, create a new string from the first, middle, and last characters of each input string.
Exercise Purpose: This exercise practices Complex Concatenation. It requires multiple independent extractions and organizing them into a single result, common when generating IDs or codes from user data.
Given Input: s1 = "America" s2 = "Japan"
Expected Output: AJrpan
Hint
- Extract the first, middle, and last character for
s1, then do the same fors2. - Finally, concatenate all six characters in the order: (s1_first, s2_first, s1_mid, s2_mid, s1_last, s2_last).
Solution
Explanation to Solution:
- Parallel Extraction: We perform the same logic on two different variables (
s1ands2). - Order of Operations: The concatenation
res = ...follows the specific sequence requested. - String Immutability: Note that we aren’t changing
s1ors2; we are creating an entirely new string variableresto hold the combination.
Exercise 5. Reverse a given string
Practice Problem: Write a program to reverse a given string.
Exercise Purpose: Reversing a string is a classic logic-building exercise. In Python, this is most efficiently done via Slicing, demonstrating the language’s ability to manipulate sequences using “steps.” It is a prerequisite for solving problems like palindrome detection.
Given Input: str1 = "PYnative"
Expected Output: evitanYP
Hint
- Use the slicing syntax
string[start:stop:step]. - To reverse a string, leave the start and stop blank and set the step to
-1.
Solution
Explanation to Solution:
[::-1]: This is the “slicing” operator. The first two colons indicate we are taking the entire range of the string (from start to finish).- The
-1Step: The third value represents the increment. A negative value tells Python to traverse the string backward, effectively reversing the order of characters.
Exercise 6. Find the last position of a given substring
Practice Problem: Write a program to find the last index of the substring “Emma” in a given string.
Exercise Purpose: While the .find() method searches from the beginning of a string, the .rfind() method (Reverse Find) locates the most recent occurrence of a specified pattern. This functionality is essential when parsing file paths or URLs that require identification of the final delimiter.
Given Input: str1 = "Emma is a data scientist who knows Python. Emma works at google."
Expected Output: Last occurrence of Emma starts at index 43
Hint
Use the built-in string method .rfind(). It returns the highest index where the substring is found.
Solution
Explanation to Solution:
str1.rfind("Emma"): This method scans the string from right to left. It identifies the starting index of the last instance of “Emma.”- Index Accuracy: Even though it searches from the right, the index returned is still calculated from the left (index 0), maintaining consistency with standard Python indexing.
Exercise 7. Split a string on hyphens
Practice Problem: Write a program to split a given string on hyphens and display each substring.
Exercise Purpose: This exercise introduces the concept of tokenization. Dividing strings into smaller components based on delimiters, such as commas, spaces, or hyphens, is a common technique for processing CSV files, logs, and user-entered lists.
Given Input: str1 = "Emma-is-a-data-scientist"
Expected Output:
Displaying each substring:
Emma
is
a
data
scientist
Hint
Use the .split() method. Pass the hyphen "-" as the argument to tell Python exactly where to “cut” the string.
Solution
Explanation to Solution:
str1.split("-"): This method breaks the string at every occurrence of the hyphen and returns a List of strings.- The Loop: Since the result is a list, we use a
forloop to iterate through the list and print each individual “token” on a new line.
Exercise 8. Find all occurrences of a substring in a given string by ignoring the case
Practice Problem: Write a program to find the total count of the substring “USA” in a given string, ignoring the case (i.e., both “usa” and “USA” should be counted).
Exercise Purpose: This exercise addresses case normalization. In practical data science and web scraping applications, text data is frequently inconsistent. Converting all text to lowercase prior to processing is considered a standard best practice.
Given Input: str1 = "Welcome to USA. usa awesome, isn't it?"
Expected Output: The USA count is: 2
Hint
- Use the
.lower()method on both the main string and the substring. - Then, use the
.count()method to find how many times the substring appears.
Solution
Explanation to Solution:
.lower(): This method creates a temporary version of the string where all letters are lowercase. This ensures that “USA”, “usa”, and “Usa” all look identical to the computer..count(): A built-in string method that returns the number of non-overlapping occurrences of a substring. By running this on the normalized version of the text, we get a case-insensitive count.
Exercise 9. String characters balance test
Practice Problem: Write a program to check if two strings are balanced. For example, strings s1 and s2 are balanced if all the characters in s1 are present in s2. The character’s position doesn’t matter.
Exercise Purpose: This exercise focuses on membership testing. This fundamental concept is utilized in data validation, such as verifying whether a password contains required characters or determining if a search query matches a database entry.
Given Input:
Case 1: s1 = "yn", s2 = "PyNative"
Case 2: s1 = "ynf", s2 = "PyNative"
Expected Output:
Case 1: True
Case 2: False
Hint
Solution
Explanation to Solution:
for char in s1: We only need to iterate through the “test” string (s1) to see if its requirements are met by the source string (s2).if char in s2: Theinoperator is a highly optimized way in Python to check for the existence of a substring or character.break: This is an efficiency step. Once we find a single character that is not ins2, we don’t need to check the rest of the string; we already know it is unbalanced.
Exercise 10. Vowel Counter
Practice Problem: Write a program to count the total number of vowels (a, e, i, o, u) in a given string.
Given Input: str1 = "Hello World"
Expected Output: Vowel Count: 3
Hint
- Create a string containing all vowels
"aeiouAEIOU". - Loop through the input string and check if each character exists within your vowel string using the
inkeyword.
Solution
Explanation to Solution:
vowels = "aeiouAEIOU": We include both lowercase and uppercase to ensure the program is case-insensitive without needing extra methods.if char in vowels: Theinoperator is a highly readable and efficient way to check for a match within a collection.- Increment Logic: Every time the condition is met, the
countvariable increases by 1.
Exercise 11. Prefix/Suffix Check
Practice Problem: Check if a given URL starts with “https” and ends with “.com”.
Exercise Purpose: This exercise teaches Boolean Validation. Methods like .startswith() and .endswith() are cleaner and less error-prone than manual slicing for verifying file formats, protocols, or naming conventions.
Given Input: str1 = "https://google.com"
Expected Output: Is valid URL: True
Hint
- Use
str1.startswith("https")andstr1.endswith(".com"). - Combine them using the
andoperator to ensure both conditions are met.
Solution
Explanation to Solution:
startswith(): ReturnsTrueif the string begins with the specified prefix..endswith(): ReturnsTrueif the string finishes with the specified suffix.- Logical
and: This ensures the result is onlyTrueif both specific parts of the string are present, which is perfect for simple URL or filename validation.
Exercise 12. Swap Case
Practice Problem: Write a program to toggle the case of all characters in a string (uppercase becomes lowercase and vice versa).
Exercise Purpose: This demonstrates Case Transformation. Though simple, it is often used in search algorithms to normalize data or in text editors to provide “Toggle Case” functionality.
Given Input: str1 = "PyThOn"
Expected Output: pYtHoN
Hint
Python has a dedicated built-in method called .swapcase() that handles this transformation in a single step.
Solution
Explanation to Solution:
.swapcase(): This method iterates through the string internally. If a character isA-Z, it converts it toa-z. If it’sa-z, it converts it toA-Z.- Non-Alphabetic Chars: Symbols and numbers are ignored by this method, leaving them unchanged and preventing data corruption.
Exercise 13. Remove Whitespace
Practice Problem: Remove every single space from a given string, including spaces between words.
Exercise Purpose: This highlights the difference between Trimming and Filtering. While .strip() only removes leading/trailing spaces, .replace() can reach inside a string to remove characters globally.
Given Input: str1 = " P y t h o n "
Expected Output: Python
Hint
Use the .replace() method. Search for a single space " " and replace it with an empty string "".
Solution
Explanation to Solution:
.replace(" ", ""): This method looks for every instance of the first argument (a space) and swaps it for the second argument (nothing).- Global Action: Unlike some other methods,
.replace()affects the entire string, making it ideal for removing all instances of a specific “noisy” character.
Exercise 14. N-th Character Removal
Practice Problem: Write a program to remove the character at index i from a string.
Exercise Purpose: Since Python strings are Immutable (you can’t just delete a character at an index), this exercise teaches you how to “reconstruct” a string by skipping over a specific part.
Given Input: str1 = "Python", i = 2
Expected Output:
Pyhon (The character 't' at index 2 was removed)
Hint
- Use slicing to get everything before index
i, and everything after indexi. - Then, join these two parts together using the
+operator.
Solution
Explanation to Solution:
str1[:i]: This captures “Py” (indices 0 and 1). Index 2 is excluded because the “stop” value in a slice is exclusive.str1[i+1:]: This captures “hon” (indices 3, 4, and 5), effectively jumping over the character at index 2.- Immutability Bypass: Because we cannot modify
str1directly, we create a new stringresthat simply doesn’t contain the character we wanted to get rid of.
Exercise 15. String Partitioning
Practice Problem: Use the .partition() method to split a string into three parts: the part before a separator, the separator itself, and the part after it.
Exercise Purpose: .split() is great for breaking a string into many pieces. .partition() is a specialized tool that always returns a 3-tuple. It is especially useful for parsing data like email addresses or key-value pairs where the separator needs to be preserved or accounted for.
Given Input: str1 = "username@company.com", sep = "@"
Expected Output: ('username', '@', 'company.com')
Hint
- Call
str1.partition("@"). Note that if the separator isn’t found, it returns the whole string followed by two empty strings.
Solution
Explanation to Solution:
- The 3-Tuple: Unlike
split(), which discards the separator,partition()keeps it as the middle element of the result. - Consistency: It always returns exactly three elements. This makes “unpacking” very safe:
prefix, sep, suffix = str1.partition("@"). - First Occurrence: If the separator appears multiple times, it partitions only at the first occurrence.
Exercise 16. Extract File Extension
Practice Problem: Given a filename as a string, extract only the file extension (e.g., .png or .pdf).
Exercise Purpose: This exercise teaches String Parsing. In software development, you need to validate file types before processing uploads. It helps you practice finding the last occurrence of a character (the dot) to handle files with multiple dots correctly (like archive.tar.gz).
Given Input: file_name = "report_final_v2.pdf"
Expected Output: pdf
Hint
You can use file_name.split(".") and take the last element of the resulting list, or use .rfind(".") to find the last dot and slice from there.
Solution
Explanation to Solution:
.split("."): This breaks the string into a list wherever a dot appears. Formy.photo.jpg, the list is['my', 'photo', 'jpg'].[-1]: This index always grabs the very last item in the list, the extension.- Robustness: This logic works even if the filename has no dots (it returns the whole filename) or multiple dots.
Exercise 17. Lowercase First
Practice Problem: Write a program to arrange string characters such that all lowercase letters come first, followed by all uppercase letters.
Exercise Purpose: This exercise introduces Conditional Filtering and Reassembly. It’s a common pattern in data sorting: you need to group items by a specific property (in this case, “casing”) while preserving their relative order.
Given Input: str1 = "PyNaTive"
Expected Output: yaivePNT
Hint
- Create two empty strings (or lists): one for lowercase and one for uppercase.
- Loop through the input string, check each character’s case, and append it to the appropriate container. Finally, join them.
Solution
Explanation to Solution:
char.islower(): A built-in check that returnsTrueif a character is lowercase.- Two-Bucket Strategy: By separating the characters into two groups as we find them, we ensure that all “lowers” stay together and all “uppers” stay together.
"".join(...): This efficiently glues our two sorted groups back into a single final string.
Exercise 18. Count all letters, digits, and special symbols from a given string
Practice Problem: Write a program to count all letters, digits, and special symbols from a given string.
Exercise Purpose: This introduces Character Classification. Using built-in string methods like .isalpha() and .isdigit() is the standard way to validate user input and perform data cleaning.
Given Input: str1 = "P@#yn26at^&i5ve"
Expected Output:
Total counts of chars, digits, and symbols: Chars = 8 Digits = 3 Symbol = 4
Hint
- Initialize three counter variables at 0.
- Use a
forloop to iterate through every character in the string. - Use
char.isalpha()to check for letters andchar.isdigit()for numbers. - Everything else falls into the “symbol” category.
Solution
Explanation to Solution:
for char in sample_str: This loop visits every single character in the string one by one.char.isalpha(): ReturnsTrueif the character is a letter (A-Z or a-z).char.isdigit(): ReturnsTrueif the character is a number (0-9).elseblock: Since every character must be either a letter, a number, or a symbol, anything that fails the first two checks is automatically counted as a symbol.
Exercise 19. Create a mixed string using alternating characters
Practice Problem: Given two strings, s1 and s2, create a third string made of the first char of s1, then the last char of s2, Next, the second char of s1 and the second-to-last char of s2, and so on. Any left-over chars go at the end of the result.
Exercise Purpose: This exercise sharpens your ability to handle Multiple Pointer Traversal. It makes you think about coordinating indices moving in opposite directions (forward through one string and backward through another).
Given Input: s1 = "Abc" s2 = "Xyz"
Expected Output: AzbycX
Hint
- Get the length of both strings.
- Use a loop that runs for the length of the larger string.
- Inside the loop, use positive indexing for
s1and negative indexing (starting from -1) fors2.
Solution
Explanation to Solution:
s2[::-1]: This is a common Python trick to reverse a string using slicing. By reversings2first, we can simply pull characters from both strings using the same indexi.if i < s1_length: Since strings might have different lengths, these checks prevent “Index out of range” errors by ensuring the index exists before we try to access it.- Concatenation: Characters are appended to the
resultvariable one by one in the specific alternating order required.
Exercise 20. Calculate the sum and average of the digits present in a string
Practice Problem: Given a string, run a loop to calculate the sum and average of the digits that appear in the string. Ignore all other characters.
Exercise Purpose: This combines Data Extraction with Arithmetic Operations. It demonstrates how to filter relevant data (numbers) out of a “noisy” string (letters and symbols) to perform calculations.
Given Input: str1 = "PYnative29@#8496"
Expected Output: Sum is: 38 Average is 6.33
Hint
- Iterate through the string and use
.isdigit(). If a character is a digit, convert it to anint, add it to atotal_sumvariable, and increment acountvariable. - The average is calculated as: (
total sum / count).
Solution
Explanation to Solution:
char.isdigit(): This filters the string, ensuring we only attempt to perform math on actual numeric characters.int(char): Characters in a string are still “strings” even if they look like numbers. We must explicitly cast them to integers to perform addition.- Floating Point Division: In Python 3, the
/operator automatically handles decimal values, providing the precise average.
Exercise 21. Count occurrences of all characters within a string
Practice Problem: Count the frequency of every character in a string and store the results in a dictionary.
Exercise Purpose: This exercise introduces Frequency Mapping using Dictionaries. Dictionaries are essential for counting and organizing data because they store unique “keys” (the characters) and associated “values” (their counts).
Given Input: str1 = "apple"
Expected Output: {'a': 1, 'p': 2, 'l': 1, 'e': 1}
Hint
Create an empty dictionary. Loop through the string. If the character is already in the dictionary, increase its value by 1. If it isn’t, add it to the dictionary with a value of 1.
Solution
Explanation to Solution:
dict(): Initializes an empty collection to store our counts.if char in char_dict: This checks if the character has been seen before.- Key-Value Logic: If it’s a new character, we initialize it at 1. If we’ve seen it before, we simply increment the existing count. This pattern is widely used in data analysis to determine the distribution of data points.
Exercise 22. Remove empty strings from a list of strings
Practice Problem: Given a list of strings, remove any empty strings or None values from it.
Exercise Purpose: This introduces Data Cleaning. Real-world datasets often have missing or empty values. Learning to filter lists is essential to prevent your program from crashing when processing empty data points.
Given Input: str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
Expected Output: ['Emma', 'Jon', 'Kelly', 'Eric']
Hint
- You can use the
filter()function. - The
filter()function takes a function and a sequence and returns an iterator where items areTrue. PassingNoneas the function will remove all “falsy” values (like empty strings andNone).
Solution
Explanation to Solution:
filter(None, str_list): In Python, empty strings""and the valueNoneare considered “Falsy.” Whenfilteris called withNoneas its first argument, it automatically discards everything that isn’t “Truthy.”list(): Becausefilterreturns a filter object (an iterator), we wrap it inlist()to convert it back into a standard list format.
Exercise 23. Remove special symbols/punctuation from a string
Practice Problem: Write a program to remove all special symbols and punctuation from a given string.
Exercise Purpose: This exercise is a staple of Natural Language Processing (NLP). Before analyzing text like sentiment analysis, you must remove “noise” such as symbols and punctuation so the computer can focus on the words.
Given Input: str1 = "/*Jon is @developer & musician!!"
Expected Output: "Jon is developer musician"
Hint
- There are many ways to do this, but the most readable way for beginners is to use a loop.
- Iterate through the string and keep only those characters that are alphanumeric (
isalnum()) or spaces.
Solution
Explanation to Solution:
char.isalnum(): This method checks if a character is either a letter or a number. If it’s a symbol (like*,@, or!), it returnsFalse.char.isspace(): We explicitly check for spaces; otherwise, the words would all get mashed together (e.g., “Jonisdevelopermusician”).- String Building: We start with an empty string and “build” the clean version character by character.
Or Use the regex in Python. See Python regex replace.
Exercise 24. Remove all characters from a string except integers
Practice Problem: Write a program to extract only the numeric digits from a mixed string and combine them into a single string.
Exercise Purpose: This is a core part of Data Extraction. Often when scraping web data or reading OCR text from images, you get strings like “Price: $25.00”. This exercise teaches you how to strip away the “noise” such as currency, labels, and spaces to get the raw numerical data for calculations.
Given Input: str1 = "I am 25 years and 10 months old"
Expected Output: 2510
Hint
- Use a loop to check every character.
- Use the
.isdigit()method to identify numbers. Since strings are immutable, you’ll want to join the digits together into a new string or a list.
Solution
Explanation to Solution:
- List Comprehension: The code
[item for item in str1 if item.isdigit()]creates a temporary list containing only the characters that are numbers. "".join(): This is the most efficient way to turn a list of characters back into a single string. It takes all the items in the list and “glues” them together using an empty string as the separator.isdigit()Logic: This ensures that spaces, letters, and punctuation are entirely ignored
Exercise 25. Find words with both letters and numbers
Practice Problem: Write a program to find and print words from a string that contain both letters and numbers.
Exercise Purpose: This exercise focuses on Contextual Filtering. In cybersecurity or system administration, you often need to find “alphanumeric” strings like Product IDs (e.g., PROD123), license keys, or mixed-character usernames. It teaches you how to look for specific patterns within individual tokens.
Given Input: str1 = "Emma25 is Data scientist50 and AI Expert"
Expected Output:
Emma25scientist50
Hint
- First, split the string into a list of words using
.split(). - Then, for each word, use
any(char.isalpha())andany(char.isdigit())to ensure it contains at least one of each.
Solution
Explanation to Solution:
str1.split(): This breaks the sentence into a list:['Emma25', 'is', 'Data', ... ].any()function: This is a clever Python tool.any(char.isalpha() for char in item)checks if at least one character in that specific word is a letter.- The
andLogic: By requiring both anisalphaand anisdigitcheck to be true, we filter out words that are only letters (like “Data”) or only numbers.
Exercise 26. Replace each special symbol with # in the following string
Practice Problem: Write a program to replace every special symbol (punctuation) in a string with a specific character, like #.
Exercise Purpose: Vital for Data Sanitization. Before sending text to certain databases or file systems that can’t handle symbols like @ or &, you often need to “mask” them. It’s also a great introduction to the string module’s built-in constants.
Given Input: str1 = "/*Jon is @developer & musician!!"
Expected Output: ##Jon is #developer # musician##
Hint
- Use the
string.punctuationconstant to get a list of all special characters. - Then, you can iterate through the string and check if each character is in that list.
Solution
Explanation to Solution:
import string: This module provides a pre-made string calledstring.punctuation, which contains all standard symbols like!"#$%&'()*+,-./:;<=>?@[\]^_{|}~.str1.replace(char, replace_char): Inside the loop, we find every instance of a specific symbol and swap it for#.- Sequential Replacement: Since we are updating
str1within the loop (str1 = str1.replace(...)), each subsequent symbol is replaced until the string is completely sanitized.
Exercise 27. Palindrome Check
Practice Problem: Write a program to check if a string is a palindrome (reads the same forward and backward).
Exercise Purpose: The palindrome check is the “Hello World” of Algorithmic Logic. It teaches you how to compare a sequence against its own reflection. In real-world applications, this concept is used in DNA sequencing and data integrity verification.
Given Input: str1 = "radar"
Expected Output: Is Palindrome: True
Hint
The most “Pythonic” way to do this is to reverse the string using slicing [::-1] and then compare it to the original string using the == operator.
Solution
Explanation to Solution:
s[::-1]: This creates a reversed copy of the string.s.lower(): Palindromes like “Racecar” would fail a standard check because “R” != “r”. Normalizing the case ensures the logic focuses only on the characters themselves.- Boolean Comparison: The
==operator returnsTrueif every character matches its corresponding character in the reversed version.
Exercise 28. Anagram Detector
Practice Problem: Write a program to check if two strings are anagrams (formed by rearranging the letters of another, such as “listen” and “silent”).
Exercise Purpose: This exercise teaches Canonical Forms. By sorting two different strings into a “standard” order (alphabetical), you can easily determine if they contain the exact same ingredients. This is a fundamental concept in data deduplication.
Given Input: s1 = "listen", s2 = "silent"
Expected Output: Are Anagrams: True
Hint
Convert both strings to lowercase. Use the sorted() function on both. If the resulting sorted lists are equal, the strings are anagrams.
Solution
Explanation to Solution:
sorted(): This is the key. When you sort “listen”, you get['e', 'i', 'l', 'n', 's', 't']. When you sort “silent”, you get the exact same list.- Comparison: If two strings have the same characters in the same quantities, their sorted lists will always be identical, making this the most efficient way to detect an anagram without complex loops.
Exercise 29. Unique Character Check
Practice Problem: Write a function to determine if a string has all unique characters. Return True if every character appears only once, otherwise return False.
Exercise Purpose: This introduces the concept of Sets. In Python, a set is an unordered collection that cannot contain duplicate items. Comparing the length of a string to the length of its “set version” is the most efficient way to check for uniqueness in O(n) time.
Given Input: str1 = "python"
str2 = "alphabet"
Expected Output:
"python" unique: True
"alphabet" unique: False
Hint
Convert the string into a set using set(str1). Since sets automatically discard duplicates, if the length of the set is equal to the length of the string, all characters must have been unique.
Solution
Explanation to Solution:
set(s): This operation scans the string and builds a collection of its unique characters. For “alphabet”, the set would be{'a', 'l', 'p', 'h', 'b', 'e', 't'}(the second ‘a’ is dropped).- Length Comparison: If the string had duplicates, the set will be shorter than the original string. If they are the same length, no characters were lost, meaning every character was unique.
Exercise 30. Title Case Logic
Practice Problem: Write a program to capitalize the first letter of every word in a sentence without using the built-in .title() method.
Exercise Purpose: This practice covers String Splitting and Indexing. While .title() exists, manually implementing it helps you understand how to isolate parts of a string, modify them, and rebuild the sentence. This is a common requirement in data transformation.
Given Input: str1 = "hello world from python"
Expected Output: Hello World From Python
Hint
Split the string into a list of words. For each word, take the first character (word[0]), convert it to uppercase, and add it to the rest of the word (word[1:]).
Solution
Explanation to Solution:
word[0].upper(): This isolates only the first letter of the word to change its case.word[1:]: This “slice” captures everything from the second character to the end, ensuring we don’t lose the rest of the word." ".join(...): This takes our list of modified words and stitches them back together with spaces in between.
Exercise 31. Remove Duplicate Characters
Practice Problem: Write a program to remove all duplicate characters from a string while keeping the remaining characters in their original order.
Exercise Purpose: This focuses on Order-Preserving Filtering. While a set() removes duplicates, it also ruins the order. This exercise teaches you how to use a loop and a “seen” tracker to clean data without scrambling it.
Given Input: str1 = "google"
Expected Output: gole
Hint
- Create an empty list called
seenand an empty string (or list) for yourresult. - Loop through the string; if a character is not in
seen, add it to bothseenandresult.
Solution
Explanation to Solution:
- The “Seen” Tracker: We use a set for
seenbecause checkingif char in seenIt is extremely fast in Python. - Conditional Addition: The
if char not in seenThe check ensures that the second ‘o’ and the second ‘g’ in “google” are skipped. - Preserving Order: Because we iterate through the original string from left to right, our
resultlist collects characters in the exact order they first appeared.
Exercise 32. Word Reversal
Practice Problem: Reverse the order of words in a given sentence, but keep the characters within the words in their original order.
Exercise Purpose: This clarifies the difference between Sequence Reversal and Character Reversal. It’s a standard interview question that tests your ability to manipulate lists of strings rather than just raw text.
Given Input: str1 = "Python is fun"
Expected Output: fun is Python
Hint
- Split the sentence into a list of words using
.split(). - Reverse that list using the
[::-1]slicing trick, and then join them back together with spaces.
Solution
Explanation to Solution:
str1.split(): This turns the string into a list of “tokens.”words[::-1]: Just like with strings, the[::-1]slice reverses the order of elements in a list.- Final Join: We use a space
" "as the glue to turn the list back into a readable sentence.
Exercise 33. Character Interleaving
Practice Problem: Given two strings of equal length, merge them by alternating characters.
Exercise Purpose: This exercise introduces Parallel Iteration. In data science, you often need to merge two separate arrays of data (like names and IDs) into a single paired format. It teaches you how to coordinate multiple indices simultaneously.
Given Input: s1 = "ABC", s2 = "xyz"
Expected Output: AxByCz
Hint
- Use a
forloop withrange(len(s1)). - In each iteration, take the character at index
ifrom both strings and add them to your result.
Solution
Explanation to Solution:
range(len(s1)): This generates indices (0, 1, 2) that we can use for both strings since they are the same length.- Alternating Addition: In the first loop,
iis 0, so we adds1[0](‘A’) ands2[0](‘x’). In the second loop, we add ‘B’ and ‘y’, and so on. - Manual Zip: While Python has a
zip()function that does this more elegantly, doing it with a loop builds a stronger understanding of how indices work.
Exercise 34. Longest Word
Practice Problem: Write a program to find the longest word in a given sentence. If there is a tie, return the first one found.
Exercise Purpose: This exercise practices Comparison Logic and State Tracking. It’s a fundamental pattern in programming: iterating through a collection while keeping track of the “best” (or longest/largest) item found so far.
Given Input: str1 = "The quick brown fox jumps over the lazy dog"
Expected Output: Longest word: quick
Note: “brown” and “jumps” are also 5 letters, but “quick” appears first.
Hint
- Split the sentence into a list of words. Initialize a variable
longestas an empty string. - Loop through the list and, if the current word’s length is greater than the length of
longest, updatelongest.
Solution
Explanation to Solution:
str1.split(): Converts the sentence into an iterable list.- State Tracking: By keeping the
longestword in a variable outside the loop, we ensure we only need to pass through the list exactly once. This isO(n)efficiency. - Strict Comparison (
>): Using “greater than” ensures that if two words have the same length, we keep the one that appeared first in the string.
Exercise 35. Acronym Creator
Practice Problem: Write a program to generate an acronym from a given phrase (e.g., “Random Access Memory” becomes “RAM”).
Exercise Purpose: This exercise focuses on String Transformation. It teaches you how to extract specific metadata (the first letter) from tokens and combine them into a new, condensed format.
Given Input: str1 = "Random Access Memory"
Expected Output: RAM
Hint
- Split the string into words.
- Use a loop or list comprehension to grab the character at index
[0]of every word, and then use.join()to put them together.
Solution
Explanation to Solution:
- List Comprehension:
[word[0] for word in str1.split()]is a concise way to create a list of just the first letters. .upper(): This ensures the acronym is properly capitalized even if the input phrase was in lowercase..join(): Glues the individual letters together without any spaces.
Exercise 36. Word Frequency
Practice Problem: Count the occurrences of each word in a string and store the result in a dictionary.
Exercise Purpose: This is the word-level version of character counting. It introduces Frequency Mapping at scale, which underpins search engine indexing and “word cloud” generation.
Given Input: str1 = "apple banana apple cherry banana apple"
Expected Output: {'apple': 3, 'banana': 2, 'cherry': 1}
Hint
- Convert the string to lowercase and split it. Use a dictionary to keep track of counts.
- If a word is already in the dictionary, increment its value; otherwise, add it with a value of 1.
Solution
Explanation to Solution:
.lower(): Normalizes the data so that “Apple” and “apple” are counted as the same word..get(word, 0): This is a pro-tip! It tries to find the word in the dictionary. If the word doesn’t exist yet, it returns0instead of crashing, allowing you to add1safely.- Dynamic Storage: The dictionary automatically grows as new, unique words are encountered.
Exercise 37. First Non-Repeating Character
Practice Problem: Find the first character in a string that does not repeat anywhere else.
Exercise Purpose: This exercise demonstrates Multi-Pass Algorithms. You cannot solve this in a single pass because you won’t know if a character repeats until you see the whole string. It teaches you to use a frequency map to guide a second traversal.
Given Input: str1 = "swiss"
Expected Output: w
Hint
- First, build a frequency dictionary of all characters.
- Then, loop through the original string one more time and return the first character whose count in the dictionary is 1.
Solution
Explanation to Solution:
- Efficiency: This is an
O(n)solution. We look at the string twice, which is much faster than checking every character and then scanning the rest of the string for its twin (O(n2)). - Why the second loop?: Dictionaries in modern Python preserve order, but looping through the string itself ensures we find the very first character that met our criteria in its original position.
Exercise 38. String Rotation Check
Practice Problem: Write a program to check if one string is a rotation of another (e.g., “waterbottle” is a rotation of “erbottlewat”).
Exercise Purpose: This exercise teaches Algorithmic Cleverness. While you could try to rotate the string manually in a loop, there is a “cheat code” logic that involves string concatenation, which is much more efficient.
Given Input: s1 = "waterbottle" s2 = "erbottlewat"
Expected Output: Is Rotation: True
Hint
If you concatenate a string with itself (s1 + s1), it will contain every possible rotation of that string. Then, simply check if s2 is a substring of that doubled string.
Solution
Explanation to Solution:
- The Doubling Trick:
waterbottlewaterbottlecontains “erbottlewat” starting at the 3rd index. This trick covers all circular shifts. - Length Guard: We check
len(s1) != len(s2)immediately. If they aren’t the same length, they can’t possibly be rotations, saving us unnecessary computation. inoperator: Python’s substring search is highly optimized, making this check very fast.
