Python String Manipulation Exercises
Python String Manipulation Practice Questions
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, sostring.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(), notlower(). - 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, raisesTypeError."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, andjoin()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, sojoin()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 inif, index 0 evaluates to False. - Option 2 – Correct: Using
"Python" in textreturnsTrueif the substring exists, which is the most Pythonic and reliable approach. - Option 3 – Incorrect:
index()raises aValueErrorif 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
inoperator 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.
Example:
text = "Solviyo"
print(text[1:4]) # Output: "olv" (end index excluded)
print(text[-3:]) # Output: "iyo" (last 3 characters)
print(text[::-1]) # Output: "oyivloS" (reversed string)
Key takeaways:
- 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], andjoin()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()andjoin()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.maketransneeds exact mapping length; using "*"*10 works, but less readable. - Option 3 – Incorrect: Modifies
textcorrectly, 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 == 0sets alternating case; spaces are skipped usingif 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
ifin 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"].
- "Solviyo" → length 7 (odd) → uppercase → "SOLVIYO"
- "Python" → length 6 (even) → reversed → "nohtyP"
- "Exercises" → length 9 (odd) → uppercase → "SESICREXE"
- Join words → "SOLVIYO nohtyP SESICREXE".
- Option 3 – Incorrect: No transformation applied.
- 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, andjoin()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.
Explore More Python Exercises
You may also like these Python exercises:
Test Your Python String Manipulation Knowledge
Practicing Python String Manipulation? Don’t forget to test yourself later in our Python Quiz.
About This Exercise: Python – String Manipulation
String manipulation is one of the most essential skills in Python, and at Solviyo, we’ve built a dedicated set of exercises with explanations and answers to help you master it. Whether you are working on simple tasks like slicing and concatenation or advanced topics like formatting and regular expressions, our Python string manipulation exercises will strengthen your understanding and prepare you for interviews, exams, and real-world projects.
We start with the fundamentals. Our beginner-friendly exercises cover basic operations such as joining strings, splitting text, changing case, trimming whitespace, and using string methods effectively. Each exercise includes a clear explanation and answer, so you don’t just see the solution—you understand the logic behind it. Alongside these, our Python MCQs test your conceptual knowledge and help reinforce what you’ve practiced.
Once the basics are in place, we move into more advanced areas of string manipulation. You’ll work on exercises involving string formatting with f-strings and the format() method, searching within strings, replacing patterns, and handling escape characters. We also include Python MCQs with answers and explanations, ensuring that you’re confident in applying these concepts in multiple scenarios.
For learners aiming to level up further, we include challenging exercises involving regular expressions (regex). These tasks train you to validate inputs, extract patterns, and perform advanced text searches. Each regex-based exercise comes with a detailed explanation and answer, helping you avoid common mistakes and build practical skills you can use in real-world projects like log analysis, text parsing, or data cleaning.
Our approach at Solviyo is hands-on and learner-focused. Every exercise is paired with explanations and answers to guide you step by step, while MCQs provide extra practice to check your understanding. This balance between coding exercises and quizzes ensures you not only know how to manipulate strings but also when and why to use specific methods or techniques.
By practicing regularly, you’ll gain confidence in solving problems that involve text processing, user input handling, and data formatting. These are skills that employers and academic programs look for, making string manipulation an essential area of focus in Python.
Start your Python string manipulation journey today with Solviyo’s exercises, MCQs, explanations, and answers. With consistent practice, you’ll sharpen your coding skills, write cleaner and more efficient code, and be fully prepared for interviews, exams, and real-world programming challenges.