String Operations#
Python strings (str) are immutable sequences of characters. They can be created with single quotes, double quotes, or triple quotes.
Through indexing, slicing, and a rich set of built-in methods, string handling in Python is very convenient.
Creating Strings#
Strings can be enclosed in single quotes ' or double quotes " — both work the same way:
1
2
3
4
5
6
7
8
9
10
11
12
| s1 = "Hello, World!"
s2 = 'Python is easy to learn'
# When the string contains quotes, use the other type to wrap it
s3 = "It's a good day"
s4 = 'He said: "Hello"'
# Triple quotes can span multiple lines
s5 = """Line one
Line two
Line three"""
print(s5)
|
Basic String Operations#
Concatenation and Repetition#
1
2
3
4
5
6
7
8
9
10
| first = "Hello"
last = "World"
# Concatenation
greeting = first + ", " + last + "!"
print(greeting) # Hello, World!
# Repetition
line = "-" * 20
print(line) # --------------------
|
Get Length: len()#
1
2
| s = "Python"
print(len(s)) # 6
|
Indexing and Slicing#
Python strings can be accessed by index to get a single character. Indices start at 0, and negative indices count from the end:
1
2
3
4
5
6
7
8
| s = "Python"
# 012345
# -6-5-4-3-2-1
print(s[0]) # P (1st character)
print(s[5]) # n (6th character)
print(s[-1]) # n (last character)
print(s[-2]) # o (second to last character)
|
Slicing extracts a substring using the syntax s[start:end:step]:
1
2
3
4
5
6
7
| s = "Python"
print(s[0:3]) # Pyt (indices 0, 1, 2)
print(s[2:]) # thon (from index 2 to the end)
print(s[:4]) # Pyth (from the beginning to index 3)
print(s[::2]) # Pto (every 2nd character)
print(s[::-1]) # nohtyP (reverse string)
|
Python 3.6 and above recommends using f-strings . Add f before the string and use {} to embed variables or expressions:
1
2
3
4
5
6
7
8
9
10
11
12
| name = "Alice"
age = 25
score = 92.5
print(f"Hello, {name}! You are {age} years old.")
# Hello, Alice! You are 25 years old.
print(f"Average score: {score:.1f}")
# Average score: 92.5
print(f"2 to the power of 10 = {2 ** 10}")
# 2 to the power of 10 = 1024
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| price = 1234567.89
print(f"{price:,}") # 1,234,567.89 (thousands separator)
print(f"{price:.2f}") # 1234567.89 (2 decimal places)
print(f"{price:,.0f}") # 1,234,568 (thousands separator, no decimals)
ratio = 0.1234
print(f"{ratio:.1%}") # 12.3% (percentage)
num = 42
print(f"{num:05d}") # 00042 (zero-padded to 5 digits)
print(f"{num:>10}") # right-aligned, width 10
print(f"{num:<10}") # left-aligned
print(f"{num:^10}") # centered
|
Common String Methods#
Case Conversion#
1
2
3
4
5
6
| s = "Hello, World!"
print(s.upper()) # HELLO, WORLD!
print(s.lower()) # hello, world!
print(s.title()) # Hello, World! (capitalize first letter of each word)
print(s.swapcase()) # hELLO, wORLD! (swap case)
|
Strip Whitespace#
1
2
3
4
5
6
7
8
9
| s = " Hello, World! "
print(s.strip()) # "Hello, World!" (strip both sides)
print(s.lstrip()) # "Hello, World! " (strip left side)
print(s.rstrip()) # " Hello, World!" (strip right side)
# You can also specify which characters to strip
s2 = "###Python###"
print(s2.strip("#")) # Python
|
Find and Replace#
1
2
3
4
5
6
7
| s = "I love Python, Python is great"
print(s.find("Python")) # 7 (index of first occurrence)
print(s.find("Java")) # -1 (returns -1 if not found)
print(s.count("Python")) # 2 (number of occurrences)
print(s.replace("Python", "Go")) # I love Go, Go is great
print(s.replace("Python", "Go", 1)) # I love Go, Python is great (replace only 1st occurrence)
|
Split and Join#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # split(): split a string, returns a list
csv = "Alice,Bob,Charlie"
names = csv.split(",")
print(names) # ['Alice', 'Bob', 'Charlie']
sentence = "I love Python"
words = sentence.split() # split by whitespace (handles multiple spaces automatically)
print(words) # ['I', 'love', 'Python']
# join(): join a list into a string
result = " - ".join(names)
print(result) # Alice - Bob - Charlie
path_parts = ["home", "user", "documents"]
path = "/".join(path_parts)
print(path) # home/user/documents
|
Check Start and End#
1
2
3
4
5
| filename = "report_2026.pdf"
print(filename.startswith("report")) # True
print(filename.endswith(".pdf")) # True
print(filename.endswith(".xlsx")) # False
|
Check String Content#
1
2
3
4
5
6
| print("123".isdigit()) # True (all digits)
print("abc".isalpha()) # True (all letters)
print("abc123".isalnum()) # True (letters or digits)
print(" ".isspace()) # True (all whitespace)
print("Hello".isupper()) # False
print("HELLO".isupper()) # True
|
Strings Are Immutable#
Once created, strings cannot be modified . Every operation produces a new string:
1
2
3
4
5
6
| s = "Hello"
# s[0] = "h" # Error! Strings do not support index assignment
# Correct approach: create a new string
s = s.lower()
print(s) # hello
|
Practical Examples#
Check for a Palindrome#
1
2
3
| word = "racecar"
is_palindrome = word == word[::-1]
print(is_palindrome) # True
|
Count Character Frequency#
1
2
3
4
| text = "hello world"
for char in set(text):
if char != " ":
print(f"'{char}' appears {text.count(char)} time(s)")
|
Multi-line Text Processing#
1
2
3
4
5
| data = "Alice,25,Taipei\nBob,30,Kaohsiung\nCharlie,22,Taichung"
for line in data.strip().split("\n"):
name, age, city = line.split(",")
print(f"{name} lives in {city}, age {age}")
|