Which of the following statements about Python strings is correct?
Understanding Python strings
Option 1 – Incorrect: Strings are immutable, so you cannot change individual characters in place.
Option 2 – Incorrect: Strings can contain a mix of letters, digits, symbols, and whitespace.
Option 3 – Correct: Strings are immutable in Python, meaning once defined, the content cannot be altered. If you want changes, you must create a new string.
Option 4 – Incorrect: Strings can be indexed and sliced, just like lists.
Key takeaways:
Strings are immutable sequences of Unicode characters.
You can access parts of a string using indexing or slicing, but you cannot reassign characters.
To modify a string, build a new one using concatenation, slicing, or string methods like replace().
Which of the following Python snippets correctly finds the length of a string?
Finding the length of a string
Option 1 – Incorrect: Python strings do not have a length() method.
Option 2 – Incorrect: length() is not a built-in Python function.
Option 3 – Incorrect: len() is a built-in function, not a string method, so string.len() is invalid.
Option 4 – Correct: len(string) is the proper way to find the length of a string in Python.
Example:
text = "Python"
print(len(text)) # Output: 6
Key takeaways:
Use the built-in len() function to find the number of characters in a string.
Spaces, digits, and special symbols also count towards string length.
What will be stored in variable result after executing the following code?
text = "Python Programming"
result = text.lower()
Using the lower() method
Option 1 – Incorrect: This would be the result of upper(), not lower().
Option 2 – Correct: lower() converts all characters in the string to lowercase → "python programming".
Option 3 – Incorrect: This is the original string without changes.
Option 4 – Incorrect: There is no built-in method that produces alternating capitalization like this.
Example:
text = "HELLO World"
print(text.lower()) # Output: hello world
Key takeaways:
lower() converts all characters to lowercase.
upper() converts all characters to uppercase.
These methods are often used when normalizing text for comparison.
Which of the following code snippets correctly concatenates two strings "Hello" and "World" with a space in between?
Concatenating strings in Python
Option 1 – Correct: Using the + operator with a space string results in "Hello World".
Option 2 – Incorrect: Python strings do not have a concat() method.
Option 3 – Incorrect: There is no built-in concat() function in Python.
Option 4 – Incorrect: The * operator repeats a string by an integer, not combines multiple strings.
Example:
first = "OpenAI"
second = "ChatGPT"
print(first + " " + second) # Output: OpenAI ChatGPT
Key takeaways:
Use the + operator to concatenate strings in Python.
The * operator can be used to repeat a string a number of times, e.g., "Hi!" * 3 → "Hi!Hi!Hi!".
Always include spaces manually if you want them between words.
In Python, what is the key difference between a string and a list regarding mutability?
Mutability in Python
Strings: Immutable, meaning once created, their content cannot be changed directly. Any modification creates a new string.
Lists: Mutable, meaning their elements can be added, removed, or updated without creating a new object.
Example:
# String example (immutable)
s = "Python"
s = s.replace("P", "J")
print(s) # Output: Jython
# List example (mutable)
l = [1, 2, 3]
l[0] = 10
print(l) # Output: [10, 2, 3]
Key takeaway: Understanding immutability is crucial when working with string manipulations in Python, as it impacts performance and memory usage.
Which of the following code snippets will output "hellohellohello" more efficiently?
Explanation:
"hello" + "hello" + "hello" → Produces the correct output but uses multiple concatenations.
"hello" * 2 + "hello" → Also correct but less direct than repetition.
"hello" + 3 → Invalid, raises TypeError.
"hello" * 3 → Most efficient and concise way to repeat a string three times.
Key takeaway: String repetition with * is more efficient than concatenating multiple strings.
What will be the value of cleaned_text after executing the following code?
text = " Python Programming "
cleaned_text = text.strip()
Using the strip() method
Option 1 – Incorrect: Only removes leading spaces? Actually, this keeps trailing spaces. Wrong.
Option 2 – Incorrect: Only removes trailing spaces? Actually, keeps leading spaces. Wrong.
Option 3 – Correct: strip() removes both leading and trailing whitespace → "Python Programming".
Option 4 – Incorrect: strip() does not remove internal words or truncate the string.
Example:
text = " Solviyo "
print(text.strip()) # Output: "Solviyo"
Key takeaways:
strip() removes leading and trailing whitespace by default.
lstrip() removes only leading spaces; rstrip() removes only trailing spaces.
Useful for cleaning user input or text data.
Which of the following snippets correctly reverses the order of words in the string "Welcome to Solviyo"?
Reversing the order of words using split() and join()
Option 1 – Incorrect: join() is applied without reversing, so the order of words remains the same.
Option 2 – Correct: split() divides the string into a list of words, words[::-1] reverses the list, and join() combines them → "Solviyo to Welcome".
Option 3 – Incorrect: text[::-1] reverses all characters, not the word order → "oyivloS ot emocleW".
Option 4 – Incorrect: reverse() returns None, so join() fails.
Example:
text = "Learn Python at Solviyo"
words = text.split()
reversed_text = " ".join(words[::-1])
print(reversed_text) # Output: "Solviyo at Python Learn"
Key takeaways:
Use split() to convert a string into a list of words.
Reversing a list can be done with slicing [:: -1].
Use join() to convert a list back into a string.
What will be the value of updated_text after executing the following code?
text = "Welcome to Solviyo"
updated_text = text.replace("Solviyo", "Python")
Using the replace() method
Option 1 – Incorrect: replace() changes the string when the target substring exists.
Option 2 – Correct: replace("Solviyo", "Python") substitutes "Solviyo" with "Python" → "Welcome to Python".
Option 3 – Incorrect: Reverses the order, which replace() does not do.
Option 4 – Incorrect: replace() does not append the new string, it replaces only the target substring.
Example:
text = "Solviyo is amazing"
new_text = text.replace("Solviyo", "Python")
print(new_text) # Output: "Python is amazing"
Key takeaways:
replace() is used to substitute one substring with another in a string.
The original string is not modified; replace() returns a new string.
You can chain multiple replace() calls for multiple substitutions.
Which of the following snippets correctly checks whether the word "Python" exists in the string "Welcome to Solviyo Python course"?
Checking if a substring exists using in
Option 1 – Incorrect: find() returns the index of the substring or -1 if not found. If used directly in if, index 0 evaluates to False.
Option 2 – Correct: Using "Python" in text returns True if the substring exists, which is the most Pythonic and reliable approach.
Option 3 – Incorrect: index() raises a ValueError if the substring does not exist, so comparing to -1 is incorrect.
Option 4 – Incorrect: Python strings do not have a contains() method.
Example:
text = "Learn Python at Solviyo"
if "Python" in text:
print("Found") # Output: Found
Key takeaways:
The in operator is the safest and most readable way to check for substrings.
Avoid using find() in conditions without checking for -1 explicitly.
index() can be used if you want the position, but it raises exceptions if not found.
Which of the following statements about string slicing in Python is correct?
Understanding string slicing in Python
Option 1 – Correct: Negative indices count from the end of the string, e.g., text[-1] gives the last character.
Option 2 – Incorrect: The end index in slicing is exclusive, not included in the result.
Option 3 – Incorrect: A step of zero in slicing raises a ValueError; it cannot be used.
Option 4 – Incorrect: Slicing works with strings, lists, tuples, and other sequence types.
Negative indices are useful to access elements from the end.
Slicing syntax: text[start:end:step].
The end index is always exclusive; adjust accordingly when slicing.
What will be the output of the following code?
text = "Solviyo Python Exercises"
words = text.split()
reversed_words = [word[::-1] for word in words]
result = " ".join(reversed_words)
print(result)
Reversing each word in a string
Option 1 – Incorrect: This is the original string without changes.
Option 2 – Incorrect: Reverses the entire string, not each word individually.
Option 3 – Incorrect: This reverses the word order, but does not reverse each word.
Option 4 – Correct: Each word is reversed individually using word[::-1], and join() combines them → "oyivloS nohtyP sesicrexE".
Step-by-step reasoning:
Split text into words: ["Solviyo", "Python", "Exercises"]
Reverse each word: ["oyivloS", "nohtyP", "sesicrexE"]
Join words with space: "oyivloS nohtyP sesicrexE"
Key takeaways:
Use list comprehensions to manipulate each word in a string.
[:: -1] reverses strings efficiently.
Combine split() and join() for word-level transformations.
Which of the following snippets will replace all vowels in the string "Solviyo Exercises" with "*"?
Replacing vowels in a string
Option 1 – Incorrect: Works only for lowercase vowels, misses uppercase vowels.
Option 2 – Incorrect: str.maketrans needs exact mapping length; using "*"*10 works, but less readable.
Option 3 – Incorrect: Modifies text correctly, but less efficient due to repeated replacements.
Option 4 – Correct: List comprehension checks each character; if it's a vowel (ignoring case), it replaces with "*", else keeps it → "*olv*y* *x*rc*s*s".
Step-by-step reasoning:
Iterate over each character in the string.
Check if the lowercase of character is in "aeiou".
Replace vowels with "*" and keep consonants unchanged.
Join all characters back into a string.
Key takeaways:
List comprehensions can efficiently transform strings character by character.
c.lower() ensures case-insensitive replacement.
This approach scales better for larger strings compared to multiple replace() calls.
What will be the value of result after executing the following code?
text = " Solviyo Python Exercises "
words = text.strip().split()
result = "_".join([word.upper() for word in words if len(word) > 5])
print(result)
Filtering, transforming, and joining words in a string
Option 1 – Correct: strip() removes leading/trailing spaces, split() creates words list, word.upper() converts to uppercase, and words with length > 5 are included → "SOLVIYO_PYTHON_EXERCISES".
Option 2 – Incorrect: Excludes "EXERCISES", which also has length > 5, so it's wrong.
Option 3 – Incorrect: Excludes "PYTHON", which has length > 5, so it's wrong.
Option 4 – Duplicate of correct Option 1 – technically correct; this will be the confirmed answer.
Step-by-step reasoning:
text.strip() → "Solviyo Python Exercises"
split() → ["Solviyo", "Python", "Exercises"]
Filter words with length > 5 → ["Solviyo", "Python", "Exercises"]
Convert to uppercase → ["SOLVIYO", "PYTHON", "EXERCISES"]
Join with "_" → "SOLVIYO_PYTHON_EXERCISES"
Key takeaways:
Combine strip(), split(), and list comprehensions for complex string manipulations.
Conditional expressions in list comprehensions allow filtering words based on length or other criteria.
join() is useful for creating formatted strings from lists.
What will be the output of the following code?
text = "Solviyo Python Exercises"
result = []
for word in text.split():
temp = ""
for char in word:
if char.lower() not in "aeiou":
temp += char
result.append(temp)
final = "-".join(result)
print(final)
Removing vowels from each word
Option 1 – Incorrect: This is the original string with all vowels, so wrong.
Option 2 – Incorrect: Misses that "Exercises" has 2 "e" vowels removed, leaving one "e"; partially wrong.
Option 3 – Incorrect: Some vowels not removed correctly.
Option 4 – Correct: Each character is checked; if it is not a vowel, it is appended. Words are joined by "-". Result → "Slvy-Pythn-Exrcss".
Step-by-step reasoning:
Split text: ["Solviyo", "Python", "Exercises"]
Remove vowels from each word:
"Solviyo" → "Slvy"
"Python" → "Pythn"
"Exercises" → "Exrcss"
Join with "-" → "Slvy-Pythn-Exrcss"
Key takeaways:
Nested loops are useful for character-level string processing.
Use char.lower() in "aeiou" to handle vowels in a case-insensitive way.
Joining lists with join() helps produce a formatted output string.
What will be the output of the following code?
text = "Solviyo Python Exercises"
result = "".join([char.upper() if i % 2 == 0 else char.lower() for i, char in enumerate(text) if char != " "])
print(result)
Alternating uppercase and lowercase letters, ignoring spaces
Option 1 – Incorrect: Keeps spaces, which are removed in the comprehension.
Option 2 – Incorrect: Incorrect placement of upper/lowercase; slightly off.
Option 3 – Incorrect: Converts all letters to uppercase, ignoring alternation.
Option 4 – Correct: enumerate(text) provides index; i % 2 == 0 sets alternating case; spaces are skipped using if char != " " → "SoLvIyOpYtHoNeXeRcIsEs".
Step-by-step reasoning:
Remove spaces: "SolviyoPythonExercises"
Enumerate indices and letters.
Apply alternating uppercase/lowercase based on even/odd indices.
Join characters into a single string → "SoLvIyOpYtHoNeXeRcIsEs"
Key takeaways:
Use enumerate() for index-based operations on strings.
List comprehensions allow filtering and conditional transformations in one line.
Skipping characters (like spaces) is easy using if in comprehensions.
What will be the output of the following code?
text = "Solviyo Python Exercises"
words = text.split()
result = []
for word in words:
if len(word) % 2 == 0:
result.append(word[::-1])
else:
result.append(word.upper())
final = " ".join(result)
print(final)
Conditional word transformation based on word length
Option 1 – Incorrect: Only converts odd-length words to uppercase but misses reversing even-length words.
Option 2 – Correct: Splits the text into words → ["Solviyo", "Python", "Exercises"].
Option 4 – Incorrect: All words uppercase, ignores length-based rules.
Step-by-step reasoning:
Split text into words.
Check each word's length:
Odd → uppercase
Even → reverse
Append transformed word to result list.
Join result list with spaces → final string.
Key takeaways:
Use conditionals inside loops for word-level transformations.
Reversing a string: word[::-1], uppercase: word.upper().
Combining split(), loops, and join() allows complex string manipulations.
What will be the output of the following code?
text = "Solviyo Python Exercises"
result = [word[0].upper() + "".join([c.lower() for c in word[1:]]) for word in text.split()]
final = "-".join(result)
print(final)
Capitalizing the first letter of each word and joining with "-"
Option 1 – Incorrect: Though text looks similar, the joining character is "-", not space; Option 2 is precise.
Option 2 – Correct:
word[0].upper() capitalizes the first letter of each word.
[c.lower() for c in word[1:]] converts remaining letters to lowercase.
text.split() splits the string into words → ["Solviyo", "Python", "Exercises"].
Join words with "-" → "Solviyo-Python-Exercises".
Option 3 – Incorrect: Converts entire word to uppercase, not just the first letter.
Option 4 – Incorrect: Converts entire word to lowercase, ignores capitalization.
Step-by-step reasoning:
Split string: ["Solviyo", "Python", "Exercises"]
Transform each word: first letter uppercase, rest lowercase.
Result list: ["Solviyo", "Python", "Exercises"]
Join with "-" → "Solviyo-Python-Exercises"
Key takeaways:
Use list comprehensions for word-level transformations in a single line.
Capitalizing first letter: word[0].upper(), rest lowercase: word[1:].lower().
Joining words with custom separators: "-".join(list).
Which of the following snippets will replace all consonants in "Solviyo Python Exercises" with "*" while keeping vowels unchanged?
Replacing consonants with "*" while keeping vowels intact
Option 1 – Correct: Uses a list comprehension to iterate over each character. If the character is a vowel (c.lower() in "aeiou"), keep it; otherwise replace with "*".
Option 2 – Incorrect: Replaces vowels with "*" instead of consonants.
Option 3 – Incorrect: Only replaces vowels; consonants remain unchanged, but the question requires the opposite.
Option 4 – Incorrect: Changes consonants to uppercase instead of replacing with "*".
Step-by-step reasoning:
Iterate each character in "Solviyo Python Exercises".
Check if the character is a vowel:
Yes → keep the character.
No → replace with "*".
Join all characters into a single string → "*o*i**o *y*o* E*i*i*e*"
Key takeaways:
List comprehensions are ideal for character-level conditional transformations.
Use c.lower() to handle uppercase and lowercase letters uniformly.
Joining characters back with "".join() gives the final string.
Which snippet will reverse the letters of every second word in the string "Solviyo Python Exercises" while keeping the other words unchanged?
Reversing letters of every second word in a string
Option 1 – Correct: Uses enumerate(words) to get index and word. Reverses the word if index is odd (i % 2 == 1), else keeps it unchanged → "Solviyo nohtyP Exercises".
Option 2 – Incorrect: Reverses words with even indices instead of odd, so output is different.
Option 3 – Incorrect: Reverses the entire string, not individual words.
Option 4 – Incorrect: Converts all words to uppercase, does not reverse any words.
Step-by-step reasoning:
Split string into words → ["Solviyo", "Python", "Exercises"]
Enumerate indices:
Index 0 → "Solviyo" → keep
Index 1 → "Python" → reverse → "nohtyP"
Index 2 → "Exercises" → keep
Join words with space → "Solviyo nohtyP Exercises"
Key takeaways:
enumerate() allows index-based operations in list comprehensions.
Conditional transformations (like reversing words at specific positions) are easily handled in one line.
Always join the transformed list back with " ".join() for final string output.
Quick Recap of Python String Manipulation Concepts
If you are not clear on the concepts of String Manipulation, you can quickly review them here before practicing the exercises. This recap highlights the essential points and logic to help you solve problems confidently.
What is a String in Python
In Python, a string is a sequence of characters enclosed in quotes (single, double, or triple quotes). Strings are immutable, meaning once created, you cannot change them in-place — any operation returns a new string.
Test string content — alphabetic, numeric, whitespace, lowercase/uppercase
Practical Code Examples for String Manipulation
# Change case
text = "PyThOn Is AwEsoME!"
print(text.lower()) # 'python is awesome!'
print(text.upper()) # 'PYTHON IS AWESOME!'
print(text.title()) # 'Python Is Awesome!'
print(text.swapcase()) # 'pYtHoN iS aWeSoMe!'
# Trim whitespace
raw = " Canada "
clean = raw.strip() # 'Canada'
# Split and join
sentence = "Learn Python in Tokyo"
words = sentence.split() # ['Learn', 'Python', 'in', 'Tokyo']
slug = "-".join(word.lower() for word in words) # 'learn-python-in-tokyo'
# Replace and search
bio = "I love Python. Python is great."
bio2 = bio.replace("Python", "Java") # Replace
pos = bio.find("love") # Index of substring
# Check prefix/suffix
filename = "report_2025.pdf"
if filename.endswith(".pdf"):
print("PDF file")
# Count occurrences
text = "USA USA USA"
print(text.count("USA")) # 3
# Validate content
code = "TOKYO123"
if code.isalnum():
print("Valid code")
Practicing Python String Manipulation? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python String Manipulation Exercises
Welcome to Solviyo’s Python String Manipulation exercises, designed to help you master one of the most essential skills in Python. From basic operations like slicing and concatenation to advanced topics such as formatting and regular expressions, these exercises provide hands-on practice with explanations and interactive MCQs to strengthen your understanding.
What You Will Learn
In this set of Python String Manipulation exercises, you will explore:
Basic string operations including slicing, concatenation, joining, splitting, changing case, and trimming whitespace.
Using Python string methods effectively for practical tasks.
Advanced string formatting with f-strings and the format() method.
Searching, replacing, and manipulating strings with patterns and escape characters.
Regular expressions (regex) for validating inputs, extracting patterns, and performing advanced text processing.
Applying string manipulation in real-world scenarios like log analysis, text parsing, and data cleaning.
Reinforcing concepts through interactive Python MCQs with explanations and answers.
Why Learning Python String Manipulation Matters
String manipulation is a fundamental skill in Python programming. Mastering it allows you to handle text processing, user input, and data formatting efficiently. These skills are critical for coding interviews, academic assignments, and professional projects, making you a more confident and capable Python programmer.
Start Practicing Python String Manipulation Today
By completing these exercises, you will gain confidence in handling strings in multiple contexts. Each exercise includes detailed explanations to help you understand the reasoning behind solutions. Start practicing Python String Manipulation exercises now, and develop the skills to write cleaner, more efficient Python code while preparing for real-world challenges and coding interviews.
Need a Quick Refresher?
Jump back to the Python Cheat Sheet to review concepts before solving more challenges.