Mastering Python Strings: Comprehensive Questions & Coding Exercises

Strengthen your Python string mastery with 13 real-world coding challenges spanning fundamental slicing, character sanitization, tokenization, regular expressions, and memory optimization.

Interactive Practice: Each challenge features a problem description, an expandable production-grade solution with multi-color syntax highlighting, and corresponding test assertions available in the interactive companion Jupyter notebook.

13 Python String Coding Exercises 🔝

Click Show Solution on any exercise to reveal the Python code and expected output:

1. Multi-line String Length & Line Splitting

Calculate total character count and total line count of a multi-line string.

Solution:

doc = """Welcome to Python
String Tutorials
at plus2net.com"""

total_chars = len(doc)
total_lines = len(doc.splitlines())
print(f"Chars: {total_chars}, Lines: {total_lines}")

Output:

Chars: 50, Lines: 3
2. Initial Capitalization without title() Side Effects

Capitalize only the first letter while keeping subsequent uppercase characters intact.

Solution:

text = "welcome to Plus2Net Python"
result = text[0].upper() + text[1:] if text else ""
print(result)

Output:

Welcome to Plus2Net Python
3. Symmetrical Centering with Asterisks

Center a string and fill both sides with asterisks equal to half of its length.

Solution:

name = "plus2net"
pad = len(name) // 2
centered = name.center(len(name) + pad * 2, "*")
print(centered)

Output:

****plus2net****
4. International Caseless Matching (casefold vs. lower)

Demonstrate why casefold() matches German sharp 'ß' while lower() fails.

Solution:

s1 = "dDcßeF"
s2 = "DDCSSef"
print("lower() equal:   ", s1.lower() == s2.lower())
print("casefold() equal:", s1.casefold() == s2.casefold())

Output:

lower() equal:    False
casefold() equal: True
5. Bounded Substring Occurrence Counting

Count occurrences of 'co' and 'o' across specific slice index offsets.

Solution:

s = "Welcome to Python"
print("Count 'co':       ", s.count('co'))
print("Count 'o' [4:10]: ", s.count('o', 4, 10))

Output:

Count 'co':        1
Count 'o' [4:10]:  2
6. Inverting Strings via Extended Slicing

Reverse a string in linear O(N) time using Python's native C step index.

Solution:

word = "plus2net"
reversed_word = word[::-1]
print("Reversed:", reversed_word)

Output:

Reversed: ten2sulp
7. Symmetrical Palindrome Verification

Verify whether a phrase reads the same backward after sanitizing punctuation.

Solution:

def is_palindrome(text: str) -> bool:
    clean = [c.casefold() for c in text if c.isalnum()]
    return clean == clean[::-1]

print("'racecar': ", is_palindrome("racecar"))
print("'Panama':  ", is_palindrome("A man, a plan, a canal: Panama"))

Output:

'racecar':  True
'Panama':   True
8. Safe Key-Value Parsing (partition vs. split)

Use partition() to prevent unpacking ValueError crashes when delimiters are missing.

Solution:

line = "TIMEOUT"
key, sep, val = line.partition("=")
val = val if sep else "30"
print(f"Key: {key}, Value: {val}")

Output:

Key: TIMEOUT, Value: 30
9. Universal Newline Splitting with keepends

Split multiline text across Windows CRLF and Unix LF while keeping line breaks.

Solution:

mixed = "Line1\r\nLine2\nLine3"
kept = mixed.splitlines(keepends=True)
print("Preserved:", kept)

Output:

Preserved: ['Line1\r\n', 'Line2\n', 'Line3']
10. Simultaneous Character Swapping with translate()

Swap characters 'A' and 'B' in 'ABBA' in a single pass without rule collision.

Solution:

table = str.maketrans("AB", "BA")
swapped = "ABBA".translate(table)
print("Swapped:", swapped)

Output:

Swapped: BAAB
11. High-Speed Mass Punctuation Deletion

Delete all standard ASCII punctuation from text in native C using maketrans and translate.

Solution:

import string

raw = "Hello, world! Welcome to Python: fast & robust."
table = str.maketrans("", "", string.punctuation)
clean = raw.translate(table)
print(clean)

Output:

Hello world Welcome to Python fast  robust
12. Sign-Aware Leading Zero Padding (zfill)

Pad signed negative and positive numbers to 6 digits preserving sign placement.

Solution:

pos = "+42"
neg = "-42"
print(pos.zfill(6))
print(neg.zfill(6))

Output:

+00042
-00042
13. Date Extraction & ISO Conversion with Regex

Extract DD-MM-YYYY dates from text and rearrange into ISO YYYY-MM-DD.

Solution:

import re

text = "Birthday: 24-12-2002"
iso = re.sub(r"\b(\d{2})-(\d{2})-(\d{4})\b", r"\3-\2-\1", text)
print(iso)

Output:

Birthday: 2002-12-24

Practice in Google Colab & GitHub 🔝

Open in Google Colab View on GitHub

Run all 13 string coding challenges interactively in Google Colab, test your own solutions against unit assertions, and explore automated verification scripts.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer