Learning by doing. Practice this lesson with coding exercices.
Lesson 16

String manipulation

Strings are sequences of characters, like words, sentences, or even single letters. In Python, strings are one of the most versatile data types, allowing you to store and manipulate text.

String manipulation is the process of editing or transforming strings to achieve a desired format, structure, or behavior. Think of it as giving your text a makeover—whether you're combining strings, formatting them, or analyzing their contents.

Why use string manipulation?

String manipulation is an essential skill in programming because text processing is everywhere. Here are some examples:

  • Formatting user input: Capitalizing names or email addresses.
  • Analyzing text: Extracting keywords or counting occurrences.
  • Cleaning data: Removing unwanted characters or spaces.

Mastering string manipulation empowers you to write more interactive and user-friendly programs.

Basic string manipulation techniques

Concatenation: Combining strings

Concatenation means joining strings together using the + operator.

first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name
print(full_name)  # Output: John Doe

Changing case

Python provides easy-to-use methods to modify the case of a string:

  • upper(): Converts all characters to uppercase.
  • lower(): Converts all characters to lowercase.
  • title(): Capitalizes the first letter of each word.
greeting = "hello world"
print(greeting.upper())  # Output: HELLO WORLD
print(greeting.lower())  # Output: hello world
print(greeting.title())  # Output: Hello World

Stripping whitespace

Strings often have extra spaces at the beginning or end. Remove them with:

  • strip(): Removes spaces from both ends.
  • lstrip(): Removes spaces from the left.
  • rstrip(): Removes spaces from the right.
text = "  Hello, World!  "
print(text.strip())   # Output: "Hello, World!"

Finding and replacing text

  • Finding: Use find() to locate a substring’s position in a string.
  • Replacing: Use replace() to substitute part of a string.
message = "Hello, John!"
print(message.find("John"))             # Output: 7
print(message.replace("John", "Alice")) # Output: Hello, Alice!

Splitting and joining strings

  • Splitting: Use split() to divide a string into a list based on a separator.
  • Joining: Use join() to combine a list of strings into a single string.
sentence = "Python is fun"
words = sentence.split()    # Splits by spaces by default
print(words)                # Output: ['Python', 'is', 'fun']

joined_sentence = " ".join(words)
print(joined_sentence)      # Output: Python is fun

Advanced string manipulation techniques

Slicing strings

You can extract specific parts of a string using slicing. Python uses zero-based indexing.

text = "Hello, World!"
print(text[0:5])   # Output: Hello
print(text[7:12])  # Output: World

Checking string contents

Python offers several methods to check what kind of characters a string contains:

  • isalpha(): Checks if all characters are letters.
  • isdigit(): Checks if all characters are digits.
  • isalnum(): Checks if all characters are letters or digits.
name = "Alice"
age = "25"

print(name.isalpha())  # Output: True
print(age.isdigit())   # Output: True
print(name.isalnum())  # Output: True

Formatting strings

String formatting allows you to embed variables directly into strings.

  • f-strings: A modern and convenient way to format strings.
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.")  
# Output: My name is Alice and I am 30 years old.

Conclusion

String manipulation gives your programs the power to handle text creatively and efficiently. Whether it’s formatting names, cleaning up data, or analyzing text, these skills are essential for any programmer.

Dive in, practice the techniques above, and watch your coding abilities grow!

Learning by doing. Practice this lesson with coding exercices.
16
You've Completed Lesson 16

Next Up

17: Exception handling

Master exception handling in Python with this lesson! Learn to use try, except, and finally blocks to manage runtime errors and common exceptions like ZeroDivisionError, ValueError, and TypeError, making your programs more robust and user-friendly.

Start Lesson 17