Path: blob/master/python/python3_cookbook/2_strings_and_text.ipynb
1480 views
Table of Contents
- 1Â Â Strings and Text
- 1.1Â Â Splitting Strings on Any of Multiple Delimiters Using re.split
- 1.2Â Â Matching Text at the Start or End of a String
- 1.3Â Â Wildcard Patterns Way of Matching Strings Using fnmatchcase
- 1.4Â Â Matching and Searching for Text Patterns
- 1.5Â Â Searching and Replacing Text
- 1.6Â Â Stripping Unwanted Characters from Strings Using strip
- 1.7Â Â Character to Character Mapping Using translate.
- 1.8Â Â Combining and Concatenating Strings
- 1.9Â Â String Formatting
- 1.10Â Â Reformatting Text to a Fixed Number of Columns Using textwrap
Strings and Text
Some of the materials are a condensed reimplementation from the resource: Python3 Cookbook Chapter 2. Strings and Text, which originally was freely available online.
Splitting Strings on Any of Multiple Delimiters Using re.split
The separator is either a semicolon (😉, a comma (,), a whitespace ( ) or multiple whitespace.
Matching Text at the Start or End of a String
Use the str.startswith()
or str.endswith()
.
Wildcard Patterns Way of Matching Strings Using fnmatchcase
Matching and Searching for Text Patterns
Example1: Finding the position of a simple first match using str.find()
.
Example2: Match a lot of the same complex pattern, it's better to precompile the regular expression pattern first using re.compile()
.
Example3: Find all occurences in the text instead of just the first one with findall()
.
Example4: Capture groups by enclosing the pattern in parathensis.
Searching and Replacing Text
Example1: Finding the position of a simple first match using str.replace()
.
Example2: More complex replace using re.sub()
. The nackslashed digits refers to the matched group.
Example3: Define a function for the substitution.
Example4: Use .subn()
to replace and return the number of substitution made.
Example5: supply the re.IGNORECASE
flag if you want to ignore cases.
Stripping Unwanted Characters from Strings Using strip
For unwanted characters in the beginning and end of the string, use str.strip()
. And there's str.lstrip()
and str.rstrip()
for left and right stripping.
Character to Character Mapping Using translate.
Boiler plate: The method str.translate()
returns a copy of the string in which all characters have been translated using a preconstructed table using the str.maketrans()
function.
Combining and Concatenating Strings
Example1: Use .join()
when the strings you wish to combine are in a sequence.
Example2: Don't use the +
operator when unneccessary.