Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Modern Python Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Modern Python Cookbook

Modern Python Cookbook - Third Edition

By : Steven F. Lott
4.9 (17)
close
close
Modern Python Cookbook

Modern Python Cookbook

4.9 (17)
By: Steven F. Lott

Overview of this book

Python is the go-to language for developers, engineers, data scientists, and hobbyists worldwide. Known for its versatility, Python can efficiently power applications, offering remarkable speed, safety, and scalability. This book distills Python into a collection of straightforward recipes, providing insights into specific language features within various contexts, making it an indispensable resource for mastering Python and using it to handle real-world use cases. The third edition of Modern Python Cookbook provides an in-depth look into Python 3.12, offering more than 140 new and updated recipes that cater to both beginners and experienced developers. This edition introduces new chapters on documentation and style, data visualization with Matplotlib and Pyplot, and advanced dependency management techniques using tools like Poetry and Anaconda. With practical examples and detailed explanations, this cookbook helps developers solve real-world problems, optimize their code, and get up to date with the latest Python features.
Table of Contents (20 chapters)
close
close
18
Other Books You May Enjoy
19
Index

1.5 Building complicated strings from lists of strings

How can we make complicated changes to an immutable string? Can we assemble a string from individual characters?

In most cases, the recipes we’ve already seen give us a number of tools for creating and modifying strings. There are yet more ways in which we can tackle the string manipulation problem. In this recipe, we’ll look at using a list object as a way to decompose and rebuild a string. This will dovetail with some of the recipes in Chapter 4.

1.5.1 Getting ready

Here’s a string that we’d like to rearrange:

>>> title = "Recipe 5: Rewriting an Immutable String"

We’d like to do two transformations:

  • Remove the part before :.

  • Replace the punctuation with _ and make all the characters lowercase.

We’ll make use of the string module:

>>> from string import whitespace, punctuation

This has two important constants:

  • string.whitespace lists all of the whitespace characters that are also part of ASCII, including space and tab.

  • string.punctuation lists punctuation marks that are also part of ASCII. Unicode has a large domain of punctuation marks. This is a widely used subset.

1.5.2 How to do it...

We can work with a string exploded into a list. We’ll look at lists in more depth in Chapter 4:

  1. Explode the string into a list object:

    >>> title_list = list(title)
  2. Find the partition character. The index() method for a list has the same semantics as the index() method has for a string. It locates the position with the given value:

    >>> colon_position = title_list.index(’:’)
  3. Delete the characters that are no longer needed. The del statement can remove items from a list. Unlike strings, lists are mutable data structures:

    >>> del title_list[:colon_position+1]
  4. Replace punctuation by stepping through each position. In this case, we’ll use a for statement to visit every index in the string:

    >>> for position in range(len(title_list)): 
     
    ...     if title_list[position] in whitespace+punctuation: 
     
    ...         title_list[position]= ’_’
  5. The expression range(len(title_list)) generates all of the values between 0 and len(title_list)-1. This assures us that the value of position will be each value index in the list. Join the list of characters to create a new string. It seems a little odd to use a zero-length string, ’’, as a separator when concatenating strings together. However, it works perfectly:

    >>> title = ’’.join(title_list) 
     
    >>> title 
     
    ’_Rewriting_an_Immutable_String’

We assigned the resulting string back to the original variable. The original string object, which had been referred to by that variable, is no longer needed: it’s automatically removed from memory (this is known as garbage collection). The new string object replaces the value of the variable.

1.5.3 How it works...

This is a change in representation trick. Since a string is immutable, we can’t update it. We can, however, convert it into a mutable form; in this case, a list. We can make whatever changes are required to the mutable list object. When we’re done, we can change the representation from a list back to a string and replace the original value of the variable.

Lists provide some features that strings don’t have. Conversely, strings provide a number of features lists don’t have. As an example, we can’t convert a list into lowercase the way we can convert a string.

There’s an important trade-off here:

  • Strings are immutable, which makes them very fast. Strings are focused on Unicode characters. When we look at mappings and sets, we can use strings as keys for mappings and items in sets because the value is immutable.

  • Lists are mutable. Operations are slower. Lists can hold any kind of item. We can’t use a list as a key for a mapping or an item in a set because the list value could change.

Strings and lists are both specialized kinds of sequences. Consequently, they have a number of common features. The basic item indexing and slicing features are shared. Similarly, a list uses the same kind of negative index values that a string does: the expression list[-1] is the last item in a list object.

We’ll return to mutable data structures in Chapter 4.

1.5.4 See also

  • Sometimes, we need to build a string, and then convert it into bytes. See the Encoding strings – creating ASCII and UTF-8 bytes recipe for how we can do this.

  • Other times, we’ll need to convert bytes into a string. See the Decoding bytes – how to get proper characters from some bytes recipe for more information.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Modern Python Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist download Download options font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon