Python String Indexing and Manipulation Exercises
This article provides a comprehensive set of ten beginner-friendly Python string exercises covering indexing, slicing, step slicing, searching, replacing, concatenation, formatting, membership testing, length calculation, case conversion, and advanced topics like regular expressions, splitting, padding, stripping, digit checking, and practical text‑analysis examples.
Python String Indexing and Manipulation Exercises
Today we will explore string indexing in Python, a fundamental yet crucial concept. By completing the following ten exercises you will master how to access and manipulate characters within strings.
Exercise 1: Basic Indexing
Goal: Understand forward and reverse indexing.
<code>s = "Hello, World!"<br/># 访问第一个字符<br/>print(s[0]) # 输出 'H'<br/># 访问最后一个字符(反向索引)<br/>print(s[-1]) # 输出 '!'</code>Explanation: s[0] retrieves the first character of s , while s[-1] retrieves the last character.
Exercise 2: Slice Operations
Goal: Learn to extract a substring using slicing.
<code>s = "Hello, World!"<br/># 提取从第二个字符到第五个字符(不包括第五个)<br/>print(s[1:5]) # 输出 'ello'<br/># 反向切片,从倒数第三个字符到最后一个<br/>print(s[-3:]) # 输出 'rld'</code>Explanation: The slice syntax s[start:end] extracts characters from start (inclusive) to end (exclusive).
Exercise 3: Step Slicing
Goal: Understand the effect of the step parameter.
<code>s = "Hello, World!"<br/># 每隔一个字符提取<br/>print(s[::2]) # 输出 'Hlo ol!'<br/># 反向遍历整个字符串<br/>print(s[::-1]) # 输出 '!dlroW ,olleH'</code>Explanation: In s[start:end:step] , the step defines the interval between characters and can be negative for reverse traversal.
Exercise 4: Find Substring Position
Goal: Use the find method to locate a substring.
<code>s = "Hello, World!"<br/># 查找"World"在字符串中的位置<br/>position = s.find("World")<br/>print(position) # 输出 7</code>Explanation: find returns the first index of the substring or -1 if not found.
Exercise 5: Replace Substring
Goal: Use the replace method to substitute part of a string.
<code>s = "Hello, World!"<br/># 将"World"替换为"Python"<br/>new_s = s.replace("World", "Python")<br/>print(new_s) # 输出 'Hello, Python!'</code>Explanation: replace(old, new) creates a new string where every occurrence of old is replaced by new .
Exercise 6: String Concatenation
Goal: Learn to concatenate strings using the + operator.
<code>greeting = "Hello"<br/>name = "Alice"<br/>message = greeting + ", " + name + "!"<br/>print(message) # 输出 'Hello, Alice!'</code>Explanation: The + operator joins multiple strings into one.
Exercise 7: String Formatting
Goal: Use format or f‑strings to embed variables.
<code>name = "Alice"<br/>age = 25<br/># 使用format方法<br/>message = "My name is {} and I am {} years old.".format(name, age)<br/>print(message) # 输出 'My name is Alice and I am 25 years old.'<br/># 使用f-string<br/>message = f"My name is {name} and I am {age} years old."
print(message) # 同上</code>Explanation: Both format and f‑strings embed variable values into a string efficiently.
Exercise 8: Membership Test
Goal: Use the in keyword to check for a substring.
<code>s = "Hello, World!"<br/># 检查字符串是否包含"World"
contains_world = "World" in s<br/>print(contains_world) # 输出 True</code>Explanation: in returns a boolean indicating whether the left operand appears in the right operand.
Exercise 9: String Length
Goal: Use the len function to get the length of a string.
<code>s = "Hello, World!"<br/>length = len(s)<br/>print(length) # 输出 13</code>Explanation: len returns the number of characters in the string.
Exercise 10: Case Conversion
Goal: Use upper and lower to change case.
<code>s = "Hello, World!"<br/># 转换为大写<br/>uppercase = s.upper()
print(uppercase) # 输出 'HELLO, WORLD!'<br/># 转换为小写<br/>lowercase = s.lower()
print(lowercase) # 输出 'hello, world!'</code>Explanation: upper and lower return new strings in all‑uppercase or all‑lowercase.
Advanced Exercises
Exercise 11: Regular Expressions
Goal: Learn to use the re module for complex pattern matching.
<code>import re<br/><br/>text = "The quick brown fox jumps over the lazy dog."
# 搜索所有以'o'结尾的单词<br/>matches = re.findall(r'\b\w*o\b', text)
print(matches) # 输出 ['over', 'dog']<br/><br/># 替换所有以'o'结尾的单词为它们的大写形式<br/>new_text = re.sub(r'\b\w*o\b', lambda m: m.group().upper(), text)
print(new_text) # 输出 'The quick brown fox JUMPS OVER the LAZY DOG.'</code>Explanation: re.findall returns all matches; re.sub replaces matches, using \b to ensure whole‑word boundaries.
Exercise 12: Split and Join
Goal: Use split and join to break and reassemble strings.
<code>s = "apple,banana,cherry"<br/># 拆分成列表<br/>items = s.split(',')
print(items) # 输出 ['apple', 'banana', 'cherry']<br/><br/># 重新连接成字符串,使用 ';' 作为分隔符<br/>new_s = ';'.join(items)
print(new_s) # 输出 'apple;banana;cherry'</code>Exercise 13: Left and Right Padding
Goal: Use ljust and rjust to align strings.
<code>s = "Python"<br/># 左填充,总长度为10,填充字符为 '-'
left_padded = s.ljust(10, '-')
print(left_padded) # 输出 'Python-----'<br/><br/># 右填充,总长度为10,填充字符为 '-'
right_padded = s.rjust(10, '-')
print(right_padded) # 输出 '------Python'</code>Exercise 14: Strip Whitespace
Goal: Use strip to remove leading and trailing whitespace.
<code>s = " Hello, World! "
trimmed = s.strip()
print(trimmed) # 输出 'Hello, World!'</code>Exercise 15: Digit Check
Goal: Use isdigit to determine if a string consists solely of digits.
<code>s = "12345"
is_numeric = s.isdigit()
print(is_numeric) # 输出 True</code>These advanced exercises further strengthen your string‑handling abilities.
Practical Case Study: Word Frequency Counter
Imagine you are building a text‑analysis tool that counts how often each word appears in an article.
<code>from collections import Counter<br/>import re<br/><br/>text = "This is a test. This test is only a test."
# 移除标点符号并将文本转换为小写
cleaned_text = re.sub(r'[^\w\s]', '', text).lower()
# 分割文本为单词列表
words = cleaned_text.split()
# 计算每个单词的出现频率
word_counts = Counter(words)
print(word_counts)</code>Using re.sub to strip punctuation and Counter to tally frequencies makes the implementation concise and efficient.
By working through these exercises and case studies you will become proficient in Python string manipulation and be ready to apply these techniques to real‑world problems.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.