Learn Python: Strings and Text Manipulation
Strings store and manipulate textual data in Python. You can create them with single quotes, double quotes, or even triple quotes if you want to span multiple lines. Strings are treated as sequences of characters, so you can index individual positions, slice portions, and combine them with others. Python also provides helpful methods to search, replace, change case, and remove unwanted whitespace. Mastering these string operations is essential for reading user input, generating output, or processing data from files and web sources.
What will be covered
• Creating strings with various quotes.
• Common string operations: concatenation (+), repetition (*).
• Indexing and slicing strings.
• Useful string methods: lower(), upper(), strip(), find(), replace(), etc.
• Basic formatted strings (f-strings) for cleaner output.
Creating Strings
A string can be enclosed in single quotes ('Hello'), double quotes ("Hello"), or triple quotes for multi-line text. This flexibility lets you choose the most convenient way to include characters like apostrophes.
single_quoted = 'Hello'
double_quoted = "Hello"
multi_line = """This is
a multi-line
string"""
print(single_quoted)
print(double_quoted)
print(multi_line)
Use whichever form is most convenient. If your string contains a quote character, choose a different enclosing quote or use an escape character (\).
Concatenation, Repetition, and Length
In Python, + merges two strings, * repeats a string a given number of times, and len() tells you the length of the string.
greeting = "Hello" + " " + "World!"
print(greeting)
repeat_line = "Hi! " * 3
print(repeat_line)
print(len(greeting))
This displays a combined message, repeats “Hi!” three times, and prints the length of “Hello World!” (including space and punctuation).
Indexing and Slicing
Strings are sequences, so you can use brackets ([]) to access specific positions (indexing) or to extract parts (slicing). Python uses zero-based indexing, meaning the first character is at index 0.
s = "ABCDEFGHIJ"
print(s[0])
print(s[2:5])
print(s[-3:])
s[0] is 'A', s[2:5] is 'CDE', and s[-3:] grabs the last three characters "HIJ". The slice [start:end] includes start but stops before end.
Common String Methods
Python includes many built-in methods to transform and search strings:
- .lower() / .upper(): convert to lowercase or uppercase.
- .strip(): remove leading and trailing whitespace.
- .replace(old, new): replace occurrences of old with new.
- .find(substring): return the index of the first occurrence of substring, or -1 if not found.
original = " Hello, Python! "
cleaned = original.strip()
print(cleaned.upper())
print(cleaned.replace("Python", "VS Code"))
print(cleaned.find("Python"))
After stripping whitespace, the code converts the phrase to uppercase, replaces "Python" with "VS Code," and finds where "Python" starts (index 7 if zero-based).
Formatted Strings (f-strings)
f-strings let you embed variables or expressions inside curly braces for easy formatting. This is often more convenient than concatenation. Just place an f before the quotes:
first_name = "Alice"
last_name = "Smith"
message = f"Hello, {first_name} {last_name}! Nice to meet you."
print(message)
Python replaces {first_name} and {last_name} with their values, resulting in a clean, readable string.
Practice Exercises
- Create a string variable with the value " Hello, Python! ". Strip off the extra spaces, convert it to uppercase, and print the final result.
-
Write a file named fullname_greeting.py. Ask the user for their first name and last name
separately (two input calls). Use an f-string to print a greeting, such as
"Hello,
! Glad you're here." - Given s = "ABCDEFGHIJ", print the substring "CDE" using slicing. Then print the last 3 characters using negative indices. Confirm you see "CDE" and "HIJ".
- Make a string example = "Mississippi". Use .replace() to transform this string so that every "i" is replaced with "I". Print the changed string. Then use .find() to locate where "ss" first appears in "Mississippi."
- Optional: experiment with triple-quoted strings. Write a small multi-line message (two or three lines). Print it and confirm the spacing matches your expectation.
Summary
You learned how strings are created, accessed, and manipulated in Python. By using slicing, concatenation, and methods like strip(), replace(), and find(), you can handle many common tasks for managing text. Furthermore, f-strings provide a concise way to format output that includes variables or embedded expressions. These tools form the backbone of text processing in Python, whether you’re producing user prompts, reading data from files, or generating complex reports in future lessons.