9  More on strings, and text files

Warning

Any changes you make to the code on this page, including your solutions to exercises, are temporary. If you leave or reload the page, all changes will be lost. If you would like to keep your work, copy and paste your code into a separate file or editor where it can be saved permanently.

9.1 Strings

In Chapter 2 we introduced strings with some basic string operators and methods. In this chapter, we will look at additional operators and commonly used methods.

9.1.1 Reminder: Concatenation and repetition

We can concatenate strings using the addition operator (+) and repeat them with the multiplication operator (*):

9.1.2 Reminder: Indexing and slicing

We can access individual characters and substrings with indexing and slicing:

9.1.3 The in operator

We can check whether one string contains another string (as a substring) with the in operator:

9.1.4 Starting position of a substring

There are two useful methods to find the starting position of a substring: .index and .find. The difference is how they behave when the substring is not found:

  • .index raises an error (which may stop the program).
  • .find returns -1 (which we can check in our code).

We can also specify the starting index for the search:

9.1.5 Replacing a substring

We can replace all occurrences of a substring with another string using .replace:

We can also specify how many occurrences to replace:

9.1.6 Changing the case

We can change the case of strings with methods such as .capitalize, .title, .lower and .upper:

9.1.7 Stripping

We can strip (remove) leading and trailing white spaces with .strip:

There are also methods .lstrip to strip only leading white spaces and .rstrip to strip only trailing white spaces.

We can specify characters to strip instead of white spaces:

Note that “?!” here means remove any ? and ! characters, rather than the exact string “?!”.

9.1.8 Reminder: Splitting and joining

Recall the following example from Chapter 2:

If no separator is given, splitting is done by any whitespace and empty strings discarded:

To join all elements of a list of strings into a single string, we can use .join:

Exercise. The .split method always returns a list of strings, and the .join method requires all elements to be strings. How can we turn a string containing integers into a list of integers? And how can we join a list of integers back to a string?

Hint Once you have a list of strings, you can use a list comprehension to convert it to a list of integers, and vice versa.

Sample solution

primes_string = "2, 3, 5, 7, 11, 13, 17, 19, 23, 29"
primes = [int(item) for item in primes_string.split(", ")]
print(primes)

numbers = [31, 37, 41, 43, 47, 53, 59, 61, 67, 71]
numbers_string = ' & '.join([str(item) for item in numbers])
print(numbers_string)

9.1.9 Other methods

See the full list of string methods in the Python documentation.

9.2 String formatting

Suppose we have two variables, name and height, and we want to create a string like this:

Person's height is x cm.

One approach is to create the string by concatenating name, the string literal 's height is, height converted to a string, and the string literal cm.:

While this works, there are more convenient ways. Let us explore a few of them below.

9.2.1 Formatted string literals

Formatted string literals, or f-strings, let us insert the values of variables and expressions directly into strings. To create f-strings, add the letter f before the opening quote. Any portion of the string enclosed within curly brackets ({ and }) is treated as an expression and replaced by its value:

Inside the curly brackets, we can add a format specification after a colon (:). This lets us control width, alignment, padding, decimal places, etc.:

More information about formatting can be found at https://docs.python.org/3/library/string.html#formatspec.

9.2.2 The string .format method

An alternative approach is to use the .format method. This method uses a “template” string with placeholders {} that are replaced with the given arguments. These placeholders can include the same formatting specifications as described above:

9.2.3 % operator

There is also the % operator, however, it is considered outdated and should not be used in new code:

9.3 Reading and writing text files

The following example demonstrates how to open and read a text file:

Always close the file when finished reading (or writing).

It is common to read a text file line by line, especially with large files. Although there is a method named .readline() for reading one line at a time, we can use a for loop directly on the file object:

For writing, we must open the file in write (“w”) or append (“a”):

Be careful, opening a file with “w” will erase its existing contents.

When working with files, it is recommended to use the with statement. This ensures the file is automatically closed after executing the indented block (even if an error occurs):