Strings
Introduction
Strings represent text in Python. They are sequences of characters enclosed in single quotes ('), double quotes ("), or triple quotes (''' or """) for multi-line strings.
Strings in Python are immutable: once created, they cannot be changed. However, you can create new strings from existing ones using operators or methods. Python strings are Unicode by default, supporting international characters out of the box.
Strings are one of the most commonly used types in programming — for user input, displaying messages, manipulating text, and working with data. Python provides a rich set of built-in methods to work with them.
Concepts
len()- Get the length of a string..upper(),.lower(),.title(),.capitalize()- Change case..strip(),.lstrip(),.rstrip()- Remove whitespace.inoperator - Check if substring exists..find(),.index()- Find position of substring..slice [start:end]- Extract part of a string using slice notation..split(separator)- Convert string to list..replace(old, new)- Replace part of a string..join()- Join elements with a separator.
String Formatting
- f-strings (
f"text {variable}") - Modern, recommended approach. .format()method - Older but still useful.- Raw strings (
r"text") - For regex and paths. - Multi-line strings using triple quotes.
Examples
name = "Alice"
print(len(name)) # 4
print(name.upper()) # ALICE
print(" hello ".strip()) # hello
print("Script" in "Python") # False
print("Python"[2:]) # thon
# f-string formatting
age = 25
print(f"My name is {name} and I'm {age} years old.")
# Multi-line string
message = """
This is a
multi-line
string.
"""
Challenges
1. Full name length
- Create a string with your full name.
- Print its length.
💡 Show Answer
full_name = "Alice Johnson"
print(len(full_name)) # 13
print(f"'{full_name}' has {len(full_name)} characters")
2. Uppercase/lowercase
- Convert "Python" to uppercase, lowercase, title case, and capitalized.
💡 Show Answer
text = "Python"
print(text.upper()) # PYTHON
print(text.lower()) # python
print(text.title()) # Python
print(text.capitalize()) # Python
# More examples
sentence = "hello world"
print(sentence.upper()) # HELLO WORLD
print(sentence.title()) # Hello World
print(sentence.capitalize()) # Hello world
# Case conversion methods
text_mixed = "PyThOn ProGramming"
print(text_mixed.swapcase()) # pYtHoN pROgRAMMING
3. Trim whitespace
- Trim the spaces from " Hello World " and print the result.
💡 Show Answer
text = " Hello World "
print(f"'{text.strip()}'") # 'Hello World'
print(f"'{text.lstrip()}'") # 'Hello World ' (left strip)
print(f"'{text.rstrip()}'") # ' Hello World' (right strip)
# Strip specific characters
text2 = "...Hello World..."
print(text2.strip('.')) # Hello World
# Strip multiple characters
text3 = "!!!Hello World???"
print(text3.strip('!?')) # Hello World
4. Substring check
- Check whether "banana" contains "ana".
💡 Show Answer
fruit = "banana"
print("ana" in fruit) # True
print("xyz" in fruit) # False
# Case-sensitive check
print("ANA" in fruit) # False
print("ANA" in fruit.upper()) # True
# Using methods
print(fruit.count("ana")) # 1 (how many times it appears)
print(fruit.find("ana")) # 1 (position of first occurrence)
print(fruit.index("ana")) # 1 (same as find, but raises exception if not found)
# Check multiple substrings
substrings = ["ana", "ban", "xyz"]
for sub in substrings:
print(f"'{sub}' in '{fruit}': {sub in fruit}")
5. Extract "thon"
- Extract "thon" from the string "Python" using slice notation.
💡 Show Answer
language = "Python"
print(language[2:]) # thon (from index 2 to end)
print(language[-4:]) # thon (last 4 characters)
# More slicing examples
print(language[:2]) # Py (first 2 characters)
print(language[1:5]) # ytho (from index 1 to 4)
print(language[::2]) # Pto (every 2nd character)
print(language[::-1]) # nohtyP (reversed)
# Using slice object
s = slice(2, None) # equivalent to [2:]
print(language[s]) # thon
6. Split into words
- Use .split() to turn "I love Python" into a list of words.
💡 Show Answer
sentence = "I love Python"
words = sentence.split()
print(words) # ['I', 'love', 'Python']
# Split with different separators
csv_data = "apple,banana,cherry"
print(csv_data.split(',')) # ['apple', 'banana', 'cherry']
path = "home/user/documents/file.txt"
print(path.split('/')) # ['home', 'user', 'documents', 'file.txt']
# Split with limit
text = "one-two-three-four-five"
print(text.split('-', 2)) # ['one', 'two', 'three-four-five']
# Join back together
words = ['Python', 'is', 'awesome']
print(' '.join(words)) # Python is awesome
print('-'.join(words)) # Python-is-awesome
7. Replace word
- Replace "bad" with "good" in the string "This is bad".
💡 Show Answer
text = "This is bad"
print(text.replace("bad", "good")) # This is good
# Multiple replacements
text2 = "bad bad bad day"
print(text2.replace("bad", "good")) # good good good day
print(text2.replace("bad", "good", 2)) # good good bad day (limit to 2)
# Chain replacements
messy_text = " Hello,,,World!!! "
clean_text = messy_text.strip().replace(",,,", " ").replace("!!!", "!")
print(clean_text) # Hello World!
# Using str.translate for character-level replacement
translation_table = str.maketrans("aeiou", "12345")
print("hello world".translate(translation_table)) # h2ll4 w4rld
8. F-string formatting
- Create an f-string that prints:
My name is [name].
I am learning Python.
💡 Show Answer
name = "Sarah McCabe"
message = f"""My name is {name}.
I am learning Python."""
print(message)
# More f-string examples
age = 25
height = 5.8
print(f"Name: {name}, Age: {age}, Height: {height:.1f}ft")
# Expressions in f-strings
x, y = 10, 20
print(f"The sum of {x} and {y} is {x + y}")
# Formatting numbers
price = 19.99
print(f"Price: ${price:.2f}") # Price: $19.99
print(f"Price: ${price:>10.2f}") # Price: $19.99 (right-aligned)
# Date formatting
from datetime import datetime
now = datetime.now()
print(f"Current time: {now:%Y-%m-%d %H:%M:%S}")
# Debug with f-strings (Python 3.8+)
value = 42
print(f"{value=}") # value=42
9. Count vowels
- Write a function count_vowels(text) that returns how many vowels are in a string.
💡 Show Answer
def count_vowels(text):
vowels = "aeiouAEIOU"
count = 0
for char in text:
if char in vowels:
count += 1
return count
# Test the function
print(count_vowels("Hello World")) # 3
print(count_vowels("Python")) # 1
# Alternative implementations
def count_vowels_comprehension(text):
vowels = "aeiouAEIOU"
return sum(1 for char in text if char in vowels)
def count_vowels_functional(text):
vowels = set("aeiouAEIOU")
return sum(char in vowels for char in text)
def count_vowels_regex(text):
import re
return len(re.findall(r'[aeiouAEIOU]', text))
# Test all implementations
test_strings = ["Hello World", "Python", "Programming", "xyz"]
for test in test_strings:
print(f"'{test}': {count_vowels(test)} vowels")
# Count each vowel separately
def count_each_vowel(text):
vowel_counts = {}
for vowel in "aeiou":
vowel_counts[vowel] = text.lower().count(vowel)
return vowel_counts
print(count_each_vowel("Programming")) # {'a': 1, 'e': 0, 'i': 1, 'o': 1, 'u': 0}
10. Palindrome check
- Create a function is_palindrome that takes a string parameter and returns if the parameter is a palindrome or not.
- Call the function with different string values.
💡 Show Answer
def is_palindrome(text):
# Convert to lowercase and keep only alphanumeric characters
cleaned = ''.join(char.lower() for char in text if char.isalnum())
return cleaned == cleaned[::-1]
# Test the function
print(is_palindrome("Civic")) # True
print(is_palindrome("Radar")) # True
print(is_palindrome("Long Weekends!")) # False
# More test cases
test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
"Was it a car or a cat I saw?",
"Madam",
"hello",
"12321",
"12345"
]
for test in test_cases:
result = is_palindrome(test)
print(f"'{test}' -> {result}")
# Alternative implementations
def is_palindrome_simple(text):
text = text.lower().replace(" ", "")
return text == text[::-1]
def is_palindrome_two_pointers(text):
# Clean the text
cleaned = ''.join(char.lower() for char in text if char.isalnum())
left, right = 0, len(cleaned) - 1
while left < right:
if cleaned[left] != cleaned[right]:
return False
left += 1
right -= 1
return True
def is_palindrome_recursive(text):
# Clean the text first
cleaned = ''.join(char.lower() for char in text if char.isalnum())
def check_palindrome(s, start, end):
if start >= end:
return True
if s[start] != s[end]:
return False
return check_palindrome(s, start + 1, end - 1)
return check_palindrome(cleaned, 0, len(cleaned) - 1)
# Test all implementations
test_text = "A man, a plan, a canal: Panama"
print(f"Original: {is_palindrome(test_text)}")
print(f"Two pointers: {is_palindrome_two_pointers(test_text)}")
print(f"Recursive: {is_palindrome_recursive(test_text)}")