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.
Click Show Solution on any exercise to reveal the Python code and expected output:
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
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
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****
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
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
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
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
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
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']
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
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
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
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
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.