Chapter 3: Strings Flashcards
strings are immutable, so all kinds of item or slice assignments are illegal.
>>> website = 'http://www.python.org' >>> website[-3:] = 'com' Traceback (most recent call last): File "", line 1, in ? website[-3:] = 'com' TypeError: object doesn't support slice assignment
string formatting operator
> > > format = “Hello, %s. %s enough for ya?”
values = (‘world’, ‘Hot’)
format % values
‘Hello, world. Hot enough for ya?’
The simplest string formatting is where the fields have no name, or where each name is just an index.
> > > ”{}, {} and {}”.format(“first”, “second”, “third”)
‘first, second and third’
“{0}, {1} and {2}”.format(“first”, “second”, “third”)
‘first, second and third’
The indices need not be in order like this, though.
»> “{3} {0} {2} {1} {3} {0}”.format(“be”, “not”, “or”, “to”)
‘to be or not to be’
in Python 3.6, there’s a shortcut you can use if you have variables named identically to corresponding replacement fields.
> > > from math import e
f”Euler’s constant is roughly {e}.”
“Euler’s constant is roughly 2.718281828459045.”
Replacement Field Names
> > > “{foo} {} {bar} {}”.format(1, 2, bar=4, foo=3)
‘3 1 4 2’
The indices of the unnamed arguments may also be used to request them out of order.
»> “{foo} {1} {bar} {0}”.format(1, 2, bar=4, foo=3)
‘3 2 4 1’
The center method centers the string by padding it on either side with a given fill character—spaces by
default.
> > > “The Middle by Jimmy Eat World”.center(39)
‘ The Middle by Jimmy Eat World ‘
“The Middle by Jimmy Eat World”.center(39, “”)
‘The Middle by Jimmy Eat World*’
The find method finds a substring within a larger string. It returns the leftmost index where the substring is
found. If it is not found, –1 is returned.
>>> 'With a moo-moo here, and a moo-moo there'.find('moo') 7 >>> title = "Monty Python's Flying Circus" >>> title.find('Monty') 0 >>> title.find('Python') 6 >>> title.find('Flying') 15 >>> title.find('Zirquss') -1
join is the inverse of split. It is used to join the elements of a sequence.
>>> seq = [1, 2, 3, 4, 5] >>> sep = '+' >>> sep.join(seq) # Trying to join a list of numbers Traceback (most recent call last): File "", line 1, in ? TypeError: sequence item 0: expected string, int found >>> seq = ['1', '2', '3', '4', '5'] >>> sep.join(seq) # Joining a list of strings '1+2+3+4+5' >>> dirs = '', 'usr', 'bin', 'env' >>> '/'.join(dirs) '/usr/bin/env' >>> print('C:' + '\\'.join(dirs)) C:\usr\bin\env
The lower method returns a lowercase version of the string.
‘Trondheim Hammer Dance’.lower()
‘trondheim hammer dance’
The replace method returns a string where all the occurrences of one string have been replaced by another.
> > > ‘This is a test’.replace(‘is’, ‘eez’)
‘Theez eez a test’
split is the inverse of join and is used to split a string into a sequence.
>>> '1+2+3+4+5'.split('+') ['1', '2', '3', '4', '5'] >>> '/usr/bin/env'.split('/') ['', 'usr', 'bin', 'env'] >>> 'Using the default'.split() ['Using', 'the', 'default']
The strip method returns a string where whitespace on the left and right (but not internally) has been
stripped (removed).
> > > ’ internal whitespace is kept ‘.strip()
‘internal whitespace is kept’
Similar to replace, translate replaces parts of a string, but unlike replace, translate works only with
single characters. Its strength lies in that it can perform several replacements simultaneously and can do so
more efficiently than replace.
Before you can use translate, however, you must make a translation table.
»> table = str.maketrans(‘cs’, ‘kz’)
»> ‘this is an incredible test’.translate(table)
‘thiz iz an inkredible tezt’
There are plenty of string methods that start with is, such as isspace, isdigit, or isupper, that determine
whether your string has certain properties (such as being all whitespace, digits, or uppercase), in which case the methods return True. Otherwise, of course, they return False.
isalnum, isalpha, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable,
isspace, istitle, isupper.