</> Code Editor { } Code Formatter

Python String Manipulation Exercises


1/20

Python String Manipulation Practice Questions

Correct
0%

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().

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.

Basic String Operations: Access, Concatenation, Indexing & Slicing

OperationDescriptionExample
IndexingAccess individual characters using positions (0-based) or negative indicess = "USA"
s[0] → 'U'
s[-1] → 'A'
SlicingExtract substrings via [start:stop] or [start:stop:step]s[0:2] → 'US'
s[::-1] → 'ASU'
ConcatenationJoin strings using + operator"Hello " + "Tokyo" → 'Hello Tokyo'
RepetitionRepeat strings using * operator"Go! " * 3 → 'Go! Go! Go! '

Common Built-in String Methods

Method / OperationPurpose / Description
upper() / lower() / title() / capitalize() / swapcase()Change letter casing: uppercase, lowercase, title-case, swap-case
strip() / lstrip() / rstrip()Remove whitespace (or specified characters) from both ends, left, or right
split(separator) / rsplit() / splitlines()Break a string into a list of substrings based on a delimiter or newline
join(iterable_of_strings)Combine a list (or iterable) of strings into one string using the original string as separator
replace(old, new[, count])Replace occurrences of a substring with another substring
find(sub) / rfind(sub) / index(sub) / rindex(sub)Search substring: find first or last occurrence, return index (or -1 / error if not found)
startswith(prefix) / endswith(suffix)Check if string starts/ends with given substring
count(sub)Count number of non-overlapping occurrences of substring
isalnum(), isalpha(), isdigit(), isspace(), islower(), isupper()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")

Advanced String Techniques: Combining Methods & Slicing

line = "  USA, Tokyo; Canada  "
clean_names = [name.strip().title() for name in line.replace(";", ",").split(",")]
# ['Usa', 'Tokyo', 'Canada']

Use triple quotes for multiline strings, raw strings for special characters, or encode/decode strings for UTF-8/Unicode text.

When & Why Use String Manipulation: Use Cases

  • Data cleaning — trimming whitespace, normalizing case, removing unwanted characters
  • Text parsing & processing — splitting sentences, extracting substrings, tokenization
  • Formatting output — building user-friendly text, generating filenames, slugs, reports
  • Validation & filtering — checking user input (isalnum(), endswith(), proper format)
  • Simple text tasks — case conversion, counting occurrences, search & replace, splitting/joining

Limitations & Things to Watch Out For

  • Strings are immutable — modifications create new strings, which can affect performance for very large strings
  • Some methods are case-sensitive (find, count, replace) — normalize case when needed
  • Indexing or slicing out-of-bound raises errors — ensure indices are valid

Summary: Key Takeaways

  • Python strings are immutable sequences of characters
  • Rich set of built-in methods for case conversion, trimming, splitting, joining, searching, replacing, and content validation
  • Combine methods, slicing, and iterable operations for concise string processing
  • Essential for data cleaning, parsing, validation, and formatting in Python scripts


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.