Text
stringlengths
1
9.41k
In this table, `S is a string` object, and optional arguments are enclosed in square brackets.
String methods in this table implement higher-level operations such as splitting and joining, case conversions, content tests, and substring searches and replacements. _Table 7-3.
String method calls in Python 3.0_ ``` S.capitalize() S.ljust(width [, fill]) S.center(width [, fill]) S.lower() S.count(sub [, start [, end]]) S.lstrip([chars]) S.encode([encoding [,errors]]) S.maketrans(x[, y[, z]]) S.endswith(suffix [, start [, end]]) S.partition(sep) S.expandtabs([tabsize]) S.replace(old, new...
To help you get started, though, let’s work through some code that demonstrates some of the most commonly used methods in action, and illustrates Python text-processing basics along the way. ###### String Method Examples: Changing Strings As we’ve seen, because strings are immutable, they cannot be changed in-place d...
For example, to replace two characters in the middle of a string, you can use code like this: ``` >>> S = 'spammy' >>> S = S[:3] + 'xx' + S[5:] >>> S 'spaxxy' ``` But, if you’re really just out to replace a substring, you can use the string replace method instead: ``` >>> S = 'spammy' >>> S = S.replace('mm...
It takes as arguments the original substring (of any length) and the string (of any length) to replace it with, and performs a global search and replace: ``` >>> 'aa$bb$cc$dd'.replace('$', 'SPAM') 'aaSPAMbbSPAMccSPAMdd' ``` In such a role, replace can be used as a tool to implement template replacements (e.g., in ...
Notice that this time we simply printed the result, instead of assigning it to a name—you need to assign results to names only if you want to retain them for later use. **|** ----- If you need to replace one fixed-size string that can occur at any offset, you can do a replacement again, or search for the substring ...
As we saw earlier, it’s a substring search operation just like the in expression, but find returns the position of a located substring. Another option is to use replace with a third argument to limit it to a single substitution: ``` >>> S = 'xxxxSPAMxxxxSPAMxxxx' ``` `>>> S.replace('SPAM', 'EGGS')` _# Replace all_ ...
Because strings are immutable, methods never really change the subject strings in-place, even if they are called “replace”! The fact that concatenation operations and the replace method generate new string objects each time they are run is actually a potential downside of using them to change strings.
If you have to apply many changes to a very large string, you might be able to improve your script’s performance by converting the string to an object that does support in-place changes: ``` >>> S = 'spammy' >>> L = list(S) >>> L ['s', 'p', 'a', 'm', 'm', 'y'] ``` The built-in list function (or an object const...
Because it is a method of strings (not of lists), it is called through the desired delimiter.
join puts the strings in a list (or other iterable) together, with the delimiter between list items; in this case, it uses an empty string delimiter to convert from a list back to a string.
More generally, any string delimiter and iterable of strings will do: ``` >>> 'SPAM'.join(['eggs', 'sausage', 'ham', 'toast']) 'eggsSPAMsausageSPAMhamSPAMtoast' ``` In fact, joining substrings all at once this way often runs much faster than concatenating them individually.
Be sure to also see the earlier note about the mutable bytearray string in Python 3.0 and 2.6, described fully in Chapter 36; because it may be changed in place, it offers an alternative to this list/join combination for some kinds of text that must be changed often. ###### String Method Examples: Parsing Text Anothe...
To extract substrings at fixed offsets, we can employ slicing techniques: ``` >>> line = 'aaa bbb ccc' >>> col1 = line[0:3] >>> col3 = line[8:] >>> col1 'aaa' >>> col3 'ccc' ``` Here, the columns of data appear at fixed offsets and so may be sliced out of the original string.
This technique passes for parsing, as long as the components of your data have fixed positions. If instead some sort of delimiter separates the data, you can pull out its components by splitting.
This will work even if the data may show up at arbitrary positions within the string: ``` >>> line = 'aaa bbb ccc' >>> cols = line.split() >>> cols ['aaa', 'bbb', 'ccc'] ``` The string split method chops up a string into a list of substrings, around a delimiter string.
We didn’t pass a delimiter in the prior example, so it defaults to whitespace— the string is split at groups of one or more spaces, tabs, and newlines, and we get back a list of the resulting substrings.
In other applications, more tangible delimiters may separate the data.
This example splits (and hence parses) the string at commas, a separator common in data returned by some database tools: **|** ----- ``` >>> line = 'bob,hacker,40' >>> line.split(',') ['bob', 'hacker', '40'] ``` Delimiters can be longer than a single character, too: ``` >>> line = "i'mSPAMaSPAMlumberjack" ...
You’ll see some additional string examples later in this book, but for more **|** ----- details you can also turn to the Python library manual and other documentation sources, or simply experiment interactively on your own.
You can also check the ``` help(S.method) results for a method of any string object S for more hints. ``` Note that none of the string methods accepts _patterns—for pattern-based text pro-_ cessing, you must use the Python re standard library module, an advanced tool that was introduced in Chapter 4 but is mostly outs...
Because of this limitation, though, string methods may sometimes run more quickly than the re module’s tools. ###### The Original string Module (Gone in 3.0) The history of Python’s string methods is somewhat convoluted.
For roughly the first decade of its existence, Python provided a standard library module called string that contained functions that largely mirrored the current set of string object methods.
In response to user requests, in Python 2.0 these functions were made available as methods of string objects.
Because so many people had written so much code that relied on the original string module, however, it was retained for backward compatibility. Today, you should use only string methods, not the original string module.
In fact, the original module-call forms of today’s string methods have been removed completely from Python in Release 3.0.
However, because you may still see the module in use in older Python code, a brief look is in order here. The upshot of this legacy is that in Python 2.6, there technically are still two ways to invoke advanced string operations: by calling object methods, or by calling `string` module functions and passing in the obj...
For instance, given a variable ``` X assigned to a string object, calling an object method: X.method(arguments) ``` is usually equivalent to calling the same operation through the string module (provided that you have already imported the module): ``` string.method(X, arguments) ``` Here’s an example of the metho...
There are good reasons for this, besides the fact that the module calls have gone away in Release 3.0.
For one thing, the module call scheme requires you to import the ``` string module (methods do not require imports).
For another, the module makes calls ``` a few characters longer to type (when you load the module with import, that is, not using from).
And, finally, the module runs more slowly than methods (the module maps most calls back to the methods and so incurs an extra call along the way). The original string module itself, without its string method equivalents, is retained in Python 3.0 because it contains additional tools, including predefined string consta...
Unless you really want to have to change your 2.6 code to use 3.0, though, you should consider the basic string operation calls in it to be just ghosts from the past. ###### String Formatting Expressions Although you can get a lot done with the string methods and sequence operations we’ve already met, Python also pro...
It’s never strictly required, but it can be convenient, especially when formatting text to be displayed to a program’s users.
Due to the wealth of new ideas in the Python world, string formatting is available in two flavors in Python today: _String formatting expressions_ The original technique, available since Python’s inception; this is based upon the C language’s “printf” model and is used in much existing code. _String formatting method ...
The expressions are more likely to be deprecated in later Python releases, though this should depend on the future practice of real Python programmers.
As they are largely just variations on a theme, though, either technique is valid to use today.
Since string formatting expressions are the original in this department, let’s start with them. Python defines the % binary operator to work on strings (you may recall that this is also the remainder of division, or modulus, operator for numbers).
When applied to strings, the % operator provides a simple way to format values as strings according to a format **|** ----- definition.
In short, the `% operator provides a compact way to code multiple string` substitutions all at once, instead of building and concatenating parts individually. To format strings: 1.
On the left of the % operator, provide a format string containing one or more embedded conversion targets, each of which starts with a % (e.g., %d). 2.
On the right of the % operator, provide the object (or objects, embedded in a tuple) that you want Python to insert into the format string on the left in place of the conversion target (or targets). For instance, in the formatting example we saw earlier in this chapter, the integer 1 replaces the %d in the format stri...
However, formatting allows us to combine many steps into a single operation.
It’s powerful enough to warrant a few more examples: ``` >>> exclamation = "Ni" >>> "The knights who say %s!" % exclamation 'The knights who say Ni!' >>> "%d %s %d you" % (1, 'spam', 4) '1 spam 4 you' >>> "%s -- %s -- %s" % (42, 3.14159, [1, 2, 3]) '42 -- 3.14159 -- [1, 2, 3]' ``` The first example here ...
In the second example, three values are inserted into the target string.
Note ``` that when you’re inserting more than one value, you need to group the values on the right in parentheses (i.e., put them in a tuple).
The % formatting expression operator expects either a single item or a tuple of one or more items on its right side. The third example again inserts three values—an integer, a floating-point object, and a list object—but notice that all of the targets on the left are %s, which stands for conversion to string.
As every type of object can be converted to a string (the one used when printing), every object type works with the %s conversion code.
Because of this, unless you will be doing some special formatting, %s is often the only code you need to remember for the formatting expression. Again, keep in mind that formatting always makes a new string, rather than changing the string on the left; because strings are immutable, it must work this way.
As before, assign the result to a variable name if you need to retain it. **|** ----- ###### Advanced String Formatting Expressions For more advanced type-specific formatting, you can use any of the conversion type codes listed in Table 7-4 in formatting expressions; they appear after the % character in substituti...
C programmers will recognize most of these because Python string formatting supports all the usual C printf format codes (but returns the result, instead of displaying it, like printf).
Some of the format codes in the table provide alternative ways to format the same type; for instance, %e, %f, and %g provide alternative ways to format floating-point numbers. _Table 7-4.
String formatting type codes_ **Code** **Meaning** `s` String (or any object’s str(X) string) ``` r s, but uses repr, not str ``` `c` Character `d` Decimal (integer) `i` Integer `u` Same as d (obsolete: no longer unsigned) `o` Octal integer `x` Hex integer ``` X x, but prints uppercase ``` `e` Floating-poi...
The general structure of conversion targets looks like this: ``` %[(name)][flags][width][.precision]typecode ``` The character type codes in Table 7-4 show up at the end of the target string.
Between the % and the character code, you can do any of the following: provide a dictionary key; list flags that specify things like left justification (−), numeric sign (+), and zero fills (0); give a total minimum field width and the number of digits after a decimal point; and more.
Both width and precision can also be coded as a * to specify that they should take their values from the next item in the input values. **|** ----- Formatting target syntax is documented in full in the Python standard manuals, but to demonstrate common usage, let’s look at a few examples.
This one formats integers by default, and then in a six-character field with left justification and zero padding: ``` >>> x = 1234 >>> res = "integers: ...%d...%−6d...%06d" % (x, x, x) >>> res 'integers: ...1234...1234 ...001234' ``` The `%e,` `%f, and` `%g formats display floating-point numbers in different w...
For simpler tasks, you might get by with simply converting to strings with a format expression or the str built-in function shown earlier: ``` >>> '%−6.2f | %05.2f | %+06.1f' % (x, x, x) '1.23 | 01.23 | +001.2' >>> "%s" % x, str(x) ('1.23456789', '1.23456789') ``` When sizes are not known until runtime, you c...
I haven’t told you much about dictionaries yet, so here’s an example that demonstrates the basics: ``` >>> "%(n)d %(x)s" % {"n":1, "x":"spam"} '1 spam' ``` **|** ----- Here, the (n) and (x) in the format string refer to keys in the dictionary literal on the right and fetch their associated values.
Programs that generate text such as HTML or XML often use this technique—you can build up a dictionary of values and substitute them all at once with a single formatting expression that uses key-based references: `>>> reply = """` _# Template with substitution targets_ ``` Greetings... Hello %(name)s! Your age s...
} ``` When used on the right of a format operation, this allows the format string to refer to variables by name (i.e., by dictionary key): ``` >>> "%(age)d %(food)s" % vars() '40 spam' ``` We’ll study dictionaries in more depth in Chapter 8.
See also Chapter 5 for examples that convert to hexadecimal and octal number strings with the %x and %o formatting target codes. ###### String Formatting Method Calls As mentioned earlier, Python 2.6 and 3.0 introduced a new way to format strings that is seen by some as a bit more Python-specific.
Unlike formatting expressions, formatting method calls are not closely based upon the C language’s “printf” model, and they are more verbose and explicit in intent.
On the other hand, the new technique still relies on some “printf” concepts, such as type codes and formatting specifications.
Moreover, it largely overlaps with (and sometimes requires a bit more code than) formatting expressions, and it can be just as complex in advanced roles.
Because of this, there is no best-use recommendation between expressions and method calls today, so most programmers would be well served by a cursory understanding of both schemes. **|** ----- ###### The Basics In short, the new string object’s format method in 2.6 and 3.0 (and later) uses the subject string as a...
Within the subject string, curly braces designate substitution targets and arguments to be inserted either by position (e.g., {1}) or keyword (e.g., {food}).
As we’ll learn when we study argument passing in depth in Chapter 18, arguments to functions and methods may be passed by position or keyword name, and Python’s ability to collect arbitrarily many positional and keyword arguments allows for such general method call patterns.
In Python 2.6 and 3.0, for example: `>>> template = '{0}, {1} and {2}'` _# By position_ ``` >>> template.format('spam', 'ham', 'eggs') 'spam, ham and eggs' ``` `>>> template = '{motto}, {pork} and {food}'` _# By keyword_ ``` >>> template.format(motto='spam', pork='ham', food='eggs') 'spam, ham and eggs' ``` ...
String formatting is not just for display: ``` >>> X = '{motto}, {0} and {food}'.format(42, motto=3.14, food=[1, 2]) >>> X '3.14, 42 and [1, 2]' >>> X.split(' and ') ['3.14, 42', '[1, 2]'] >>> Y = X.replace('and', 'but under no circumstances') >>> Y '3.14, 42 but under no circumstances [1, 2]' ###### A...
For instance, format strings can name object attributes and dictionary keys—as in normal Python syntax, square brackets name dictionary keys and dots denote object attributes of an item referenced by position or keyword.
The first of the **|** ----- following examples indexes a dictionary on the key “spam” and then fetches the attribute “platform” from the already imported sys module object.
The second does the same, but names the objects by keyword instead of position: ``` >>> import sys >>> 'My {1[spam]} runs {0.platform}'.format(sys, {'spam': 'laptop'}) 'My laptop runs win32' >>> 'My {config[spam]} runs {sys.platform}'.format(sys=sys, config={'spam': 'laptop'}) 'My l...
As with % expressions, to name negative offsets or slices, or to use arbitrary expression results in general, you must run expressions outside the format string itself: ``` >>> somelist = list('SPAM') >>> somelist ['S', 'P', 'A', 'M'] >>> 'first={0[0]}, third={0[2]}'.format(somelist) 'first=S, third=A' ``` `...
For the formatting method, we use a colon after the substitution target’s identification, followed by a format specifier that can name the field size, justification, and a specific type code.
Here’s the formal structure of what can appear as a substitution target in a format string: ``` {fieldname!conversionflag:formatspec} ``` In this substitution target syntax: - fieldname is a number or keyword naming an argument, followed by optional “.name” attribute or “[index]” component references. - conversi...
The `formatspec also contains nested` ``` {} format strings with field names only, to take values from the arguments list dynam ``` ically (much like the * in formatting expressions). See Python’s library manual for more on substitution syntax and a list of the available type codes—they almost completely overlap with ...
For instance, in the following {2:g} means the third argument formatted by default according to the “g” floating-point representation, {1:.2f} designates the “f” floating-point format with just 2 decimal digits, and ``` {2:06.2f} adds a field with a width of 6 characters and zero padding on the left: >>> '{0:e}, {1:....
In fact, string formatting is an alternative to some of the built-in functions that format integers to a given base: **|** ----- `>>> '{0:X}, {1:o}, {2:b}'.format(255, 255, 255)` _# Hex, octal, binary_ ``` 'FF, 377, 11111111' ``` `>>> bin(255), int('11111111', 2), 0b11111111` _# Other to/from binary_ ``` ('0b1...
It’s a more concise alternative to the string format method, and is roughly similar to formatting a single item with the % formatting expression: `>>> '{0:.2f}'.format(1.2345)` _# String method_ ``` '1.23' ``` `>>> format(1.2345, '.2f')` _# Built-in function_ ``` '1.23' ``` `>>> '%.2f' % 1.2345` _# Expression_ `...
It’s still more verbose than ``` the original % expression’s equivalent, though—which leads us to the next section. ###### Comparison to the % Formatting Expression If you study the prior sections closely, you’ll probably notice that at least for positional references and dictionary keys, the string format method lo...
In fact, in common use cases formatting expressions may be easier to code than formatting method calls, especially when using the generic %s print-string substitution target: ``` print('%s=%s' % ('spam', 42)) # 2.X+ format expression print('{0}={1}'.format('spam', 42)) # 3.0 (and 2.6) format method ``` **|*...
For example, the original `% expression can’t handle keywords, attribute references, and` binary type codes, although dictionary key references in `% format strings can often` achieve similar goals.
To see how the two techniques overlap, compare the following ``` % expressions to the equivalent format method calls shown earlier: ``` _# The basics: with % instead of format()_ ``` >>> template = '%s, %s, %s' ``` `>>> template % ('spam', 'ham', 'eggs')` _# By position_ ``` 'spam, ham, eggs' >>> template = '...
For instance, the following shows the same result generated with both techniques, with field sizes and justifications and various argument reference methods: _# Hardcoded references in both_ ``` >>> import sys >>> 'My {1[spam]:<8} runs {0.platform:>8}'.format(sys, {'spam': 'laptop'}) 'My laptop runs win32' >...
When we account for common practice in examples like this, the comparison between the format method and the % expression is even more direct (as we’ll see in Chapter 18, the **data in the method call here is special syntax that unpacks a dictionary of keys and values into individual “name=value” keyword arguments so th...
Experiment with these techniques on your own to get a feel for what they offer, and be sure to see the Python 2.6 and 3.0 library manuals for more details. **|** ----- _String format method enhancements in Python 3.1: The upcoming 3.1_ release (in alpha form as this chapter was being written) will add a thousand-se...
Add a comma before the type code to make this work, as follows: ``` >>> '{0:d}'.format(999999999999) '999999999999' >>> '{0:,d}'.format(999999999999) '999,999,999,999' ``` Python 3.1 also assigns relative numbers to substitution targets automatically if they are not included exp...
Python 3.1 will also address a major performance issue in 3.0 related to the speed of file input/output operations, which made 3.0 impractical for many types of programs.
See the 3.1 release notes for more details.
See also the _formats.py comma-insertion and_ money-formatting function examples in Chapter 24 for a manual solution that can be imported and used prior to Python 3.1. ###### Why the New Format Method? Now that I’ve gone to such lengths to compare and contrast the two formatting techniques, I need to explain why you ...
In short, although the formatting method can sometimes require more code, it also: - Has a few extra features not found in the % expression - Can make substitution value references more explicit - Trades an operator for an arguably more mnemonic method name - Does not support different syntax for single and mul...
But because the choice is currently still yours to make, let’s briefly expand on some of the differences before moving on. **|** ----- ###### Extra features The method call supports a few extras that the expression does not, such as binary type codes and (coming in Python 3.1) thousands groupings.
In addition, the method call supports key and attribute references directly.
As we’ve seen, though, the formatting expression can usually achieve the same effects in other ways: ``` >>> '{0:b}'.format((2 ** 16) −1) '1111111111111111' >>> '%b' % ((2 ** 16) −1) ValueError: unsupported format character 'b' (0x62) at index 1 >>> bin((2 ** 16) −1) '0b1111111111111111' >>> '%s' % bin((2...
The lister.py classes example we’ll meet in Chapter 30, for example, substitutes six items into a single string, and in this case the method’s {i} position labels seem easier to read than the expression’s %s: ``` '\n%s<Class %s, address %s:\n%s%s%s>\n' % (...) # Expression '\n{0}<Class {1}, address {2}:\n{3}...
This is also something of a worst-case scenario for formatting complexity, and not very common in practice; more typical use cases seem largely a tossup.
Moreover, in Python 3.1 (still in alpha release form as I write these words), numbering substitution values will become optional, thereby subverting this purported benefit altogether: ``` C:\misc> C:\Python31\python >>> 'The {0} side {1} {2}'.format('bright', 'of', 'life') 'The bright side of life' >>> ``` `>>...
Compare the effect on floating-point formatting, for example— the formatting expression is still more concise, and still seems less cluttered: ``` C:\misc> C:\Python31\python >>> '{0:f}, {1:.2f}, {2:05.2f}'.format(3.14159, 3.14159, 3.14159) '3.141590, 3.14, 03.14' >>> >>> '{:f}, {:.2f}, {:06.2f}'.format(3.141...