chapter two

2 Processing and formatting strings

 

This chapter covers

  • Using f-strings to interpolate expressions and apply formatting
  • Converting strings to other applicable data types
  • Joining and splitting strings
  • Using regular expressions for advanced string processing

Textual information is the most important form of data in almost every application. In an online shopping website, we use text to provide production descriptions. Textual data, as well as files and numeric data, can all be saved as text files, reading which all requires us to process strings. We know that machine learning is trending, and one critical machine learning specialty is termed natural language processing (NLP). NLP is concerned with extracting information from texts. Because of this, text processing is an inevitable step in preparing the data in these applications. In short, there are numerous real-life cases where we need to process and format strings properly. In this chapter, we tackle some of the most commonly encountered text processing problems.

2.1 How do I use f-strings for string interpolation and formatting?

In Python, you can format text strings in a variety of ways. One emerging approach is to use an f-string, which allows you to embed expressions inside a string literal. While you can still use other string formatting approaches, an f-string gives a more readable solution, and thus you should use f-strings as the preferred approach when you prepare strings as output.

2.1.1 Formatting strings before f-strings

2.1.2 Using f-strings to interpolate variables

2.1.3 Using f-strings to interpolate expressions

2.1.4 Applying specifiers to format f-strings

2.1.5 Discussion

2.1.6 Challenge

2.2 How do I convert strings to retrieve the represented data?

2.2.1 Checking whether strings represent alphanumeric values

2.2.2 Casting strings to numbers

2.2.3 Evaluating strings to derive their represented data

2.2.4 Discussion

2.2.5 Challenge

2.3 How do I join and split strings?

2.3.1 Joining strings with whitespaces

2.3.2 Joining strings with any delimiters

2.3.3 Splitting strings to create a list of strings

2.3.4 Discussion

2.3.5 Challenge

2.4 What are the essentials of regular expressions?

2.4.1 Using regular expressions in Python