String Basics

The most common data type you'll work with isn't numbers — it's text. Usernames, emails, articles, JSON data, HTML... all strings. This lesson systematically covers Python string operations.


1. Three Types of Quotes

Python allows three ways to define strings:

PYTHON
# Single quotes
s1 = 'Hello'

# Double quotes
s2 = "Hello"

# Triple quotes (multi-line strings)
s3 = """This is the first line
This is the second line
This is the third line"""

Single and double quotes are equivalent — pick one and stay consistent:

PYTHON
# These two are equivalent
name = 'Xiao Ming'
name = "Xiao Ming"

But if your string contains quotes, you'll need to mix:

PYTHON
# String has single quotes, wrap with double quotes
text = "It's a beautiful day"
print(text)              # It's a beautiful day

# String has double quotes, wrap with single quotes
text = 'He said: "Hello!"'
print(text)              # He said: "Hello!"

# Or use an escape character (not recommended, hurts readability)
text = 'It\'s a beautiful day'
💡 Tip: It's recommended to use double quotes consistently. English text often contains apostrophes (don't, it's) — with single quotes you'd need to escape them. Double quotes avoid this hassle.

Triple Quotes: Great for Multi-line Text

Triple quotes (""" or ''') preserve line breaks and formatting:

PYTHON
# Multi-line text with triple quotes
message = """Dear Customer,

Thank you for choosing our service. Your order has been confirmed.
Estimated delivery: 3 business days.

If you have any questions, please contact support.
Have a nice day!"""

print(message)

Output:

TEXT
Dear Customer,

Thank you for choosing our service. Your order has been confirmed.
Estimated delivery: 3 business days.

If you have any questions, please contact support.
Have a nice day!

Triple quotes are commonly used for: long text, documentation strings, and function descriptions.


2. Escape Characters

Some characters can't be written directly in a string (like newlines, tabs, or quotes themselves). Use escape characters — a backslash \ followed by a character.

Escape Meaning
\n Newline
\t Tab
\\ Backslash itself
\' Single quote
\" Double quote
PYTHON
print("First line\nSecond line")           # \n newline
print("Name:\tZhang San\tAge:\t25")        # \t tab alignment
print("C:\\Users\\XiaoMing\\Desktop")      # \\ outputs backslash
print("He said: \"Hello!\"")               # \" double quote

Output:

TEXT
First line
Second line
Name:	Zhang San	Age:	25
C:\Users\XiaoMing\Desktop
He said: "Hello!"

Example: Formatting a Table with Escape Characters (Difficulty ⭐)

PYTHON
# Use \t to align a table
print("Item\tPrice\tQty\tTotal")
print("------------------------")
print("Apple\t5.0\t3\t15.0")
print("Banana\t3.5\t5\t17.5")
print("Milk\t12.0\t2\t24.0")
▶ Try it Yourself

Output:

TEXT
Item	Price	Qty	Total
------------------------
Apple	5.0	3	15.0
Banana	3.5	5	17.5
Milk	12.0	2	24.0
💡 Tip: \t is useful for aligning text, but if content lengths vary, alignment may not be perfect. For production, use f-string formatting ({value:10} to occupy 10 character width).


3. Raw Strings

If you've ever written Windows file paths, you've experienced this pain:

PYTHON
# Oops! \n is interpreted as newline
path = "C:\Users\new_folder\documents"
print(path)
# Output: C:\Users
#        ew_folder\documents

Solution: prefix the string with r, telling Python "don't process escape characters, output as-is":

PYTHON
# ✅ Raw string — r prefix
path = r"C:\Users\new_folder\documents"
print(path)
# Output: C:\Users\new_folder\documents

In a raw string, each character is itself — \n no longer means newline, \t no longer means tab.

PYTHON
# Regex patterns (we'll use this later)
pattern = r"\d{3}-\d{8}"   # Match phone numbers: 010-12345678

# File paths
log_path = r"D:\logs\app\2026\06\error.log"

print(f"Log path: {log_path}")
⚠️ Note: The last character of a raw string cannot be a backslash — r"abc\" will error. Why? Even though \" isn't treated as an escape, the parser sees the backslash as escaping the closing quote, causing an unterminated string.


4. String Indexing

A string is a sequence of characters, each with a position (index). Python indexes start from 0:

PYTHON
text = "Python"
# Index: 0→P  1→y  2→t  3→h  4→o  5→n

print(text[0])    # P
print(text[1])    # y
print(text[5])    # n

Python also supports negative indexing, counting from right to left. -1 is the last character:

PYTHON
text = "Python"
print(text[-1])   # n (last)
print(text[-2])   # o (second to last)
print(text[-3])   # h
print(text[-6])   # P (first)

Index Diagram

TEXT
Positive:  0    1    2    3    4    5
       ┌────┬────┬────┬────┬────┬────┐
       │ P  │ y  │ t  │ h  │ o  │ n  │
       └────┴────┴────┴────┴────┴────┘
Negative: -6   -5   -4   -3   -2   -1

Example: Extract Information from an ID Number (Difficulty ⭐)

PYTHON
# Extract basic info from an ID number
id_number = "110101199001011234"

# First 6 digits: region code
address_code = id_number[:6]      # We'll cover slicing next
print(f"Region code: {address_code}")

# Digits 7-14: date of birth
birth = id_number[6:14]
year = birth[:4]
month = birth[4:6]
day = birth[6:8]
print(f"Date of birth: {year}-{month}-{day}")

# Last digit (-1): checksum
last_digit = id_number[-1]
print(f"Checksum: {last_digit}")
▶ Try it Yourself

Output:

TEXT
Region code: 110101
Date of birth: 1990-01-01
Checksum: 4
💡 Tip: string[6:14] is called slicing — we'll cover it next.


5. String Slicing

Slicing extracts a substring from a string. Syntax: string[start:end:step]

PYTHON
text = "Hello, Python!"

# Basic slice: start:end (end is exclusive)
print(text[0:5])      # Hello (characters 0 to 4)
print(text[7:13])     # Python

Shortcuts

PYTHON
text = "Hello, Python!"

print(text[:5])       # Hello — omit start, from beginning up to index 5
print(text[7:])       # Python! — omit end, from index 7 to end
print(text[:])        # Hello, Python! — everything

Step

PYTHON
text = "Hello, Python!"

print(text[::2])      # Hlo yhn! — every 2nd character
print(text[1::2])     # el,Pto — start at 1, every 2nd

Negative Step (Reversal)

PYTHON
text = "Hello, Python!"

print(text[::-1])     # !nohtyP ,olleH — reverse the entire string!
print(text[5:0:-1])   # ,olle — from index 5 to 0, reverse direction

Slice Examples

PYTHON
# Practical slicing tricks
url = "https://www.example.com"

# Remove protocol prefix
without_https = url[8:]    # www.example.com
print(without_https)

# Get domain
domain = url[8:-4]         # www.example
print(domain)

# Reverse a string
name = "racecar"
reversed_name = name[::-1]   # racecar (palindrome)
print(name == reversed_name)  # True — it's a palindrome!

# Every other character
code = "H1e2l3l4o5"
clean = code[::2]           # Hello
print(clean)

Output:

TEXT
www.example.com
www.example
True
Hello
💡 Tip: [::-1] is the classic Python way to reverse a string — simple and elegant. Note that slicing never raises IndexError — even if the start or end exceeds the string length, Python safely returns what it can.


6. Common String Methods

Strings have many built-in methods. We'll cover the most common ones here. No need to memorize everything — knowing what's available is enough; you'll memorize with practice.

Case Conversion

PYTHON
text = "Hello, Python!"

print(text.upper())         # HELLO, PYTHON!
print(text.lower())         # hello, python!
print(text.title())         # Hello, Python!
print(text.capitalize())    # Hello, python!

Stripping Whitespace

PYTHON
text = "   Hello, World!   "

print(f"|{text}|")                # |   Hello, World!   |
print(f"|{text.strip()}|")        # |Hello, World!| — both sides
print(f"|{text.lstrip()}|")       # |Hello, World!   | — left only
print(f"|{text.rstrip()}|")       # |   Hello, World!| — right only

Searching and Replacing

PYTHON
text = "Hello, Python! Python is fun!"

print(text.find("Python"))      # 7 — first occurrence position
print(text.find("Java"))        # -1 — not found, returns -1
print(text.count("Python"))     # 2 — number of occurrences

new_text = text.replace("Python", "Java")
print(new_text)                  # Hello, Java! Java is fun!

# replace can specify max replacements
partial = text.replace("Python", "Java", 1)
print(partial)                   # Hello, Java! Python is fun!

Check Methods

PYTHON
print("hello".isalpha())        # True — all letters
print("hello123".isalpha())     # False — has digits
print("12345".isdigit())        # True — all digits
print("hello123".isalnum())     # True — letters and digits
print("hello!".isalnum())       # False — has exclamation mark
print("   ".isspace())          # True — all whitespace
💡 Tip: These check methods are very useful for input validation. For example, checking if user input is all digits: if user_input.isdigit(): ensures int() conversion won't fail.

Splitting and Joining

PYTHON
# split(): string → list
sentence = "I love Python"
words = sentence.split()
print(words)                     # ['I', 'love', 'Python']

# Specify delimiter
csv_line = "Zhang San,25,Beijing"
fields = csv_line.split(",")
print(fields)                    # ['Zhang San', '25', 'Beijing']

# join(): list → string
parts = ["2026", "06", "23"]
date = "-".join(parts)
print(date)                      # 2026-06-23

Example: Data Cleaning (Difficulty ⭐⭐)

PYTHON
# Simulate dirty user input
raw_data = "   Zhang San  ,  25  ,  Beijing  \n"

# Cleaning process
# 1. strip() removes leading/trailing whitespace
cleaned = raw_data.strip()
print(f"Step 1: |{cleaned}|")

# 2. split() by comma
fields = cleaned.split(",")
print(f"Step 2: {fields}")

# 3. Strip extra spaces from each field
name = fields[0].strip()
age = fields[1].strip()
city = fields[2].strip()

print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
▶ Try it Yourself

Output:

TEXT
Step 1: |Zhang San  ,  25  ,  Beijing|
Step 2: ['Zhang San  ', '  25  ', '  Beijing']
Name: Zhang San
Age: 25
City: Beijing

7. len(): Getting String Length

len() is a built-in Python function that returns the length of a string (or other sequences):

PYTHON
text = "Hello, Python!"
print(len(text))              # 15

# Chinese characters each count as 1
chinese = "你好世界"
print(len(chinese))           # 4

# Empty string has length 0
print(len(""))                # 0

# Common use: limit input length
username = "Xiao Ming"
if len(username) < 2:
    print("Username too short")
elif len(username) > 10:
    print("Username too long")
else:
    print(f"Username '{username}' is valid")
💡 Tip: In Python 3, string length counts characters, not bytes. len("中") returns 1, not 3 (it would return 3 in Python 2). This makes string operations more intuitive.


Common Use Cases


❓ FAQ

Q Single quotes vs double quotes — which should I use? Why does Python allow both?
A Historically, Python's designers believed in giving programmers choice. C/Java programmers tend to use double quotes; JavaScript programmers use both. It's recommended to use double quotes consistently, because English often has single quotes (it's, don't, can't), so double quotes avoid escaping. More importantly, stay consistent within a project — don't mix them. ⚠️ Q: Why is the end index excluded? Like text[0:5] doesn't include index 5? A: This is Python's design philosophy — half-open intervals [start, end). Two benefits: 1) text[:5] is easy to remember (first 5 characters); 2) text[0:5] and text[5:10] seamlessly connect without overlap or gaps. You'll appreciate this design once you get used to it. Q: What's the difference between find() and index()? A: They do the same thing — find substring position. Difference: find() returns -1 when not found; index() raises an error (ValueError). Use find() for safety in daily work. Use index() when you're certain the substring exists (e.g., extracting from fixed-format data). Q: Why don't string methods modify the original string? (e.g., text.upper() doesn't change text) A: Because strings in Python are immutable. Once created, they can't be modified. text.upper() actually returns a new string; the original text stays the same. This ensures data safety — when you pass a string to a function, you can be sure it won't be secretly modified. To "modify" a string, create a new one through slicing and concatenation.

📖 Summary

  • Strings have three quote forms: single, double, triple; double quotes are recommended
  • Escape characters \n, \t, \\, etc., represent special characters
  • Raw strings r"..." prevent backslash escaping, great for paths and regex
  • Indexing starts at 0, supports negative indexing (-1 is the last character)
  • Slicing [start:end:step] extracts substrings; end is exclusive; negative step reverses
  • Common methods: strip(), split(), join(), find(), replace()
  • Check methods: isdigit(), isalpha(), isalnum(), etc., for input validation
  • Strings are immutable — all "modifications" create new strings

📝 Exercises

  1. Basic (Difficulty ⭐): Given s = "Python programming is fun!", do the following:

    • Extract the first 6 characters
    • Extract the last 4 characters
    • Reverse the entire string
    • Convert all letters to uppercase
  2. Intermediate (Difficulty ⭐⭐): Write an email validator. Given email = "user@example.com", check if:

    • It contains @
    • There's content on both sides of @ (neither side empty)
    • It ends with .com, .cn, or .org
    • Output each check result (True/False) Hint: Use find() to locate @, slicing to check both sides.
  3. Challenge (Difficulty ⭐⭐⭐): Write a data cleaner. Given:

    TEXT
    data = "   Zhang San, 25 ,  Beijing  ;  Li Si  ,  30,  Shanghai  ;  Wang Wu  ,  22,  Guangzhou  "
    

    Split by ; to get each person's data, then split by , to get each field. Use strip() to clean each field, then output a neatly aligned table:

    TEXT
    Name       Age  City
    ────────────────────
    Zhang San  25   Beijing
    Li Si      30   Shanghai
    Wang Wu    22   Guangzhou
    
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏