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.