Python Basics

Working with Strings

Working with Strings

Strings are essential for AI applications — prompts, responses, and message formatting all use strings extensively.

String Creation

# Single or double quotes
message = "Hello, AI!"
message = 'Hello, AI!'

# Multi-line strings
prompt = """
You are a helpful assistant.
Respond concisely.
"""

F-Strings (Formatted Strings)

The most powerful way to build prompts:

name = "Alice"
greeting = f"Hello, {name}!"

Common String Methods

  • .strip() — Remove whitespace
  • .lower() / .upper() — Change case
  • .split() — Split into list
  • .replace() — Replace text
  • .startswith() / .endswith() — Check patterns

Try It Yourself

Run this code example to practice what you've learned.

example.py
1# Building AI prompts with f-strings
2user_name = "Alice"
3task = "summarize this article"
4context = "You are a helpful AI assistant"
5
6# Simple f-string
7prompt = f"{context}. The user {user_name} wants you to {task}."
8print(prompt)
9
10# Multi-line prompt template
11system_prompt = f"""
12You are an AI assistant.
13User: {user_name}
14Task: {task}
15
16Guidelines:
17- Be concise
18- Be accurate
19- Be helpful
20"""
21print(system_prompt)
22
23# String methods for cleaning input
24user_input = " SUMMARIZE THIS "
25clean_input = user_input.strip().lower()
26print(f"Cleaned: '{clean_input}'")
27
28# Checking response patterns
29response = "I'll help you summarize that article."
30if response.startswith("I'll help"):
31 print("Assistant acknowledged the task!")