🌐 Unicode and Special Characters

Python 3 uses Unicode by default, making it easy to work with text in any language and special characters. Understanding Unicode is essential for handling international text and symbols.

# Basic Unicode examples
print("Hello, 世界!")  # Chinese characters
print("こんにちは")    # Japanese characters
print("안녕하세요")    # Korean characters

🎯 Unicode Basics

Unicode is a standard that assigns unique numbers to characters from all writing systems.

Basic Examples

# Different ways to represent Unicode
# Using Unicode escape sequences
print("\u0041")  # 'A'
print("\u4F60\u597D")  # '你好' (Hello in Chinese)

# Using named characters
print("\N{GRINNING FACE}")  # 😀
print("\N{HEAVY BLACK HEART}")  # ❤

# Using raw strings
print(r"\u0041")  # Prints the literal \u0041

🔍 Special Characters

Python provides ways to handle special characters and escape sequences.

# Special character examples
# Common escape sequences
print("First line\nSecond line")  # Newline
print("Tab\tseparated")  # Tab
print("Backslash: \\")  # Backslash
print("Quotes: \"Hello\"")  # Quotes

# Raw strings for paths
path = r"C:\Users\name\Documents"
print(path)

# Multi-line strings
text = """Line 1
Line 2
Line 3"""
print(text)

🎨 Common Use Cases

Here are some practical examples of working with Unicode and special characters.

# 1. Handling file paths
def normalize_path(path):
    return path.replace("\\", "/")

# 2. Creating a progress bar with symbols
def progress_bar(current, total):
    filled = "█" * int(current/total * 10)
    empty = "░" * (10 - len(filled))
    return f"[{filled}{empty}] {current/total:.0%}"

# 3. Formatting text with special characters
def format_card(title, content):
    return f"""
{'═' * (len(title) + 2)}{title}{'═' * (len(title) + 2)}{content}{'═' * (len(title) + 2)}"""

# Test the functions
print(normalize_path(r"C:\Users\name\Documents"))
print(progress_bar(7, 10))
print(format_card("Hello", "World"))

📝 Quick Practice

Let's practice working with Unicode and special characters!

Hands-on Exercise

Create a function to display a menu with Unicode box-drawing characters.

python
# Menu Display Practice
def display_menu(items):
    # TODO: Implement menu display
    # 1. Find the longest item for proper box width
    # 2. Create a box using Unicode box-drawing characters
    # 3. Display each item with a number
    # 4. Add a border around the menu
    
    # Example items: ["Option 1", "Option 2", "Option 3"]
    return ""

# Test the function
menu_items = ["New Game", "Load Game", "Settings", "Exit"]
print(display_menu(menu_items))

Solution and Explanation 💡

Click to see the solution
# Menu Display Solution
def display_menu(items):
    # Find the longest item
    max_length = max(len(item) for item in items)
    width = max_length + 4  # Add padding
    
    # Create the menu
    menu = []
    
    # Top border
    menu.append("╔" + "═" * width + "╗")
    
    # Menu items
    for i, item in enumerate(items, 1):
        menu.append(f"║ {i}. {item:<{max_length}} ║")
    
    # Bottom border
    menu.append("╚" + "═" * width + "╝")
    
    return "\n".join(menu)

# Test the function
menu_items = ["New Game", "Load Game", "Settings", "Exit"]
print(display_menu(menu_items))

Key Learning Points:

  • 📌 Used Unicode box-drawing characters
  • 📌 Used string formatting for alignment
  • 📌 Used list comprehension for width calculation
  • 📌 Used join() for final output

🎯 Key Takeaways

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent