Chapter 4: Strings and String Methods

Strings are the workhorses of every programming language. They allow us to work with text, manipulate data, format output, and communicate with users. In this chapter, you’ll master Python’s string manipulation capabilities and learn how to write clean, readable string code. Strings are sequences of characters, and Python provides powerful tools to work with them.

In this chapter you will learn:

4.1 What Is a String?

Strings are Python’s data type for storing and manipulating text. A string is an immutable sequence of characters, which means once you create a string, you cannot change its individual characters. Python strings can contain any Unicode character and are enclosed in quotes.

String Creation and Literals

You can create strings using single quotes, double quotes, or triple quotes:

>>> # Single quotes
>>> name = 'Alice'
>>> # Double quotes
>>> greeting = "Hello, world!"
>>> # Triple quotes for multi-line
>>> poem = """Roses are red,
... Violets are blue,
... Python is fun,
... For me and for you!"""

All three approaches create the same data type — the str class. Triple quotes are useful for multi-line strings or when you need to include single and double quotes in your string.

The Empty String

The empty string is simply two quotes with nothing between them:

>>> empty = ""
>>> len(empty)
0

Escape Sequences

Python uses backslashes to represent special characters:

>>> print("She said \"Hello\" to him.")
She said "Hello" to him.
>>> print("Line 1\\nLine 2")
Line 1
Line 2
>>> path = "C:\\Users\\Alice\\Desktop"
>>> print(path)
C:\\Users\\Alice\\Desktop
Escape Sequence Meaning Example
\' Single quote 'It\'s working'
\" Double quote "She said \"Hi\""
\\ Backslash "C:\\Program Files\\"
\n New line "Line 1\\nLine 2"
\t Tab "Column1\\tColumn2"
\r Carriage return "Text')

You can use raw strings (prefixed with r) to treat backslashes literally:

>>> raw_path = r"C:\Users\Alice\Desktop"
>>> print(raw_path)
C:\Users\Alice\Desktop

4.2 Accessing Characters in Strings

Strings are sequences, which means you can access individual characters using indexing. Python uses zero-based indexing, so the first character is at index 0.

String Indexing

Use square brackets with an index to access a character:

>>> word = "Python"
>>> word[0] # First character
'P'
>>> word[1]
'y'
>>> word[5] # Last character
'n'

You can also use negative indices, which start from the end of the string:

>>> word[-1] # Last character
'n'
>>> word[-2] # Second to last
'o'

String Slicing

Slicing allows you to extract substrings. The syntax is string[start:end] where start is inclusive and end is exclusive:

>>> phrase = "Python Programming"
>>> phrase[0:6] # First 6 characters
'Python'
>>> phrase[7:18] # From index 7 to 17
'Programming'
>>> phrase[7:] # From index 7 to end
'Programming'
>>> phrase[:6] # From start to index 5
'Python'

You can even use negative indices with slices:

>>> phrase[-11:-1] # 'Programming' without 'g'
'Programmin'

Strings are immutable — you cannot modify them in place. Attempting to do so raises a TypeError.

4.3 String Methods

Python provides dozens of methods for string manipulation. The most important ones are covered here. String methods create new strings rather than modifying the original, since strings are immutable.

Changing Case

Python provides methods to change the case of strings:

>>> name = "alice SMITH"
>>> name.upper()
'ALICE SMITH'
>>> name.lower()
'alice smith'
>>> name.capitalize()
'Alice smith'
>>> name.title()
'Alice Smith'

Searching in Strings

Use find() and index() to locate substrings. find() returns -1 if not found, while index() raises a ValueError:

>>> text = "Python is awesome"
>>> text.find("is")
7
>>> text.find("Java") # Not found
-1
>>> text.index("awesome")
10

Use count() to count occurrences and startswith() / endswith() for pattern matching:

>>> sentence = "The quick brown fox jumps over the lazy dog."
>>> sentence.count("the")
2
>>> sentence.startswith("The")
True
>>> sentence.endswith(".")
True

Replacing and Splitting

replace() substitutes occurrences of one substring with another:

>>> original = "I love JavaScript!"
>>> corrected = original.replace("JavaScript", "Python")
>>> corrected
'I love Python!'
>>> corrected.replace("love", "like", 1) # Replace first occurrence only
'I like Python!'

split() breaks a string into a list of substrings and join() combines them back:

>>> csv = "apple,banana,orange"
>>> fruits = csv.split(",")
>>> fruits
['apple', 'banana', 'orange']
>>> " ".join(fruits)
'apple banana orange'
>>> "\n".join(fruits)
'apple
banana
orange'

Whitespace Management

These methods help clean up strings with unwanted whitespace:

>>> messy = "   hello world   "
>>> messy.strip() # Remove both sides
'hello world'
>>> messy.lstrip() # Remove left side
'hello world   '
>>> messy.rstrip() # Remove right side
'   hello world'

Testing Methods

Methods that return True or False are great for validation:

>>> user_input = "12345"
>>> user_input.isdigit()
True
>>> user_input.isalpha()
False
>>> user_input.isalnum()
True
>>> " ".isspace()
True
>>> "hello".islower()
True
>>> "HELLO".isupper()
True

4.4 String Concatenation and Repetition

You can combine strings using the + operator or use repetition with *:

>>> first = "Hello"
>>> second = "World"
>>> first + second
'HelloWorld'
>>> first + " " + second
'Hello World'
>>> "ha " * 3
'ha ha ha '
>>> "=" * 40
'========================================'

You cannot concatenate strings with other data types directly:

>>> age = 25
>>> "Alice is " + age
TypeError: can only concatenate str (not "int") to str

Use str() to convert first, or use f-strings (coming next).

4.5 String Formatting

String formatting allows you to create readability output by inserting variables into strings. Python offers several approaches, with f-strings being the most modern and preferred method.

Traditional String Formatting

The older % operator is still available for compatibility:

>>> name = "Alice"
>>> age = 30
>>> "Name: %s, Age: %d" % (name, age)
'Name: Alice, Age: 30'

The str.format() Method

str.format() uses placeholder curly braces:

>>> "This is {} and they are {} years old.".format(name, age)
'This is Alice and they are 30 years old.'

F‑Strings — The Modern Way

F-strings (available in Python 3.6+) are the preferred method:

>>> f"Name: {name}, Age: {age}"
'Name: Alice, Age: 30'
>>> f"Next year, they will be {age + 1}"
'Next year, they will be 31'

You can format expressions directly inside the braces:

>>> price = 49.99
>>> tax_rate = 0.08
>>> f"Before tax: ${price:.2f}"
'Before tax: $49.99'
>>> f"After tax: ${price * (1 + tax_rate):.2f}"
'After tax: $53.99'

Format Specifiers

Control number formatting with format specifiers after a colon:

>>> pi = 3.141592653589793
>>> f"π to 2 decimal places: {pi:.2f}"
'π to 2 decimal places: 3.14'
>>> f"π to 4 decimal places: {pi:.4f}"
'π to 4 decimal places: 3.1416'
>>> f"Scientific notation: {pi:e}"
'Scientific notation: 3.141593e+00'
>>> number = 1000000
>>> f"Comma separator: {number:,}"
'Comma separator: 1,000,000'
>>> percentage = 0.85
>>> f"Percentage: {percentage:.1%}"
'Percentage: 85.0%'

4.6 Challenge: String Processor

Create a text processing program named text_processor.py that demonstrates various string operations. Your program should prompt the user for a text string and then display:

  1. The string in all uppercase letters
  2. The string in all lowercase letters
  3. The number of characters in the string
  4. The first character of the string
  5. The last character of the string
  6. The string with the first five characters removed
  7. The string with every occurrence of the letter "a" changed to the letter "z"
  8. Whether the string contains only digits
  9. Whether the string contains only letters
  10. The string split into individual words
Enter a string of text: Hello World

All uppercase: HELLO WORLD
All lowercase: hello world
Length: 11
First character: H
Last character: d
Without first 5 chars:  World
'a' → 'z': Hello World
Contains only digits? False
Contains only letters? False
Individual words: ['Hello', 'World']

Review Exercises

  1. Write a program that reverses a string without using the built-in reversed() function or slicing with step -1.
  2. Create a function that determines if a string is a palindrome (reads the same forwards and backwards).
  3. Use f-strings to format a receipt for a grocery store purchase with proper currency formatting and tax calculation.
  4. Write a program that extracts email addresses from a given text string using string methods.
  5. Create a simple text statistics program that counts sentences, words, and characters in a paragraph.

4.7 Working With Strings and Numbers

When you get user input using the input() function, the result is always a string. There is no direct way in Python to have users enter an integer or floating-point number interactively.

If you want to work with numbers that come from user input, you must convert them from strings to the appropriate numeric type using int() or float().

>>> num_string = "42" >>> num_string '42' >>> int(num_string) 42 >>> float(num_string) 42.0

Keep in mind that if you try to convert something that's not a number string into an integer or float, Python raises a ValueError.

>>> int("not-a-number") Traceback (most recent call last): File "", line 1, in ValueError: invalid literal for int() with base 10: 'not-a-number'

You can also convert a number back to a string:

>>> x = 42 >>> str(x) '42' >>> y = 3.14159 >>> str(y) '3.14159'

Combining Numeric Strings With Numbers

A common mistake is trying to add a number to a string without converting either one first. The + operator concatenates strings and adds numbers. It doesn't do automatic conversion:

>>> "foo" + 2 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str

The exception message tells you that you can only concatenate str to str. So, if you need to convert the number to a string, you use the str() function:

>>> "foo" + str(2) 'foo2'

The other way around works too:

>>> int("2") + 2 4

4.8 Finding a String in a String

One of the most useful string methods is .find(). As its name implies, .find() helps you find where in a string one substring occurs. The result is the index where the substring is found:

>>> phrase = "the surprise is in here somewhere" >>> phrase.find("surprise") 4

The value that .find() returns is the index of the first occurrence of the substring you pass to it. In this case, "surprise" starts at the fifth character of the string "the surprise is in here somewhere" which has index 4 because counting starts at 0.

If Python can't find a substring at all, .find() returns -1. If the substring appears more than once, .find() returns the first occurrence.

>>> phrase.find("apple") -1 >>> phrase.find("the") 0

Note that .find() looks for the entire substring. It's not searching for individual letters—it must match the exact string you pass.

4.9 Challenge: Turn Your User Into a L33t H4x0r

Write a script that takes text input from the user and translates it into "leetspeak" using the following changes to lowercase letters:

You can ignore capitalization in the translation.

Enter some text: I like turtles I 11k3 7ur7135

Hint: Remember that strings are immutable. Each time you make a conversion, you're actually creating a new string.

4.10 Summary and Additional Resources

In this chapter, you learned about Python’s string data type and its extensive suite of methods for text manipulation. Strings are immutable sequences that support indexing, slicing, formatting, and modification through methods.

Mastering string operations is crucial for text processing, data validation, and user‑friendly output in your programs.

Interactive Quiz: This chapter comes with a free online quiz to test your understanding of string manipulation in Python.

End of Chapter 4 — Strings and String Methods

100%