Strings Methods

The string data type has a lot of associated methods. Some even seem to defy the immutable property of strings (but, not really, as explained below.)

I'll provide a useful selection of methods here, and leave the rest as an exercise for the reader. I would highly recommend the following to learn more:

help(str)
In [1]:
s1 = "Hello"
s2 = 'World'
s3 = """Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts."""

Joining Strings

You can definitely join strings using the + (concatenation) operation; however what if you were give strings in a different way that make it cumbersome to glue together strings? Well, you want the .join() method. Here's how it works:

  • Choose a string to use for 'joining' other strings together. Often, a literal value is fine:
    " ".join(['a', 'b', 'c'])
    

or, a variable referring to a string:

my_str = "$"
my_str.join(['Money, get away', 'Money, get back', 'Money, it\'s a crime'])

Joining often requires a list of strings as a parameter.

In [45]:
"_".join(list(s1))
Out[45]:
'H_e_l_l_o'
In [6]:
my_str = " $ "
new_str = my_str.join(['Money, get away', 'Money, get back', 'Money, it\'s a crime'])
new_str
Out[6]:
"Money, get away $ Money, get back $ Money, it's a crime"

Splitting Strings

A useful opposite of .join() is .split(). If you are given a string of text that you wish to split up into smaller strings based on a particular component of the string. If we want to split a string based on whitespace (spaces, tabs, carriage returns, line feed characters) you simply need to call .split() with no parameters. If you want to split a string on a specific character(s) then call with them as a string parameter: .split(" $ ")

In [5]:
lyric = "To hear the softly spoken magic spells."
parts = lyric.split()
print(parts)
parts[5]
['To', 'hear', 'the', 'softly', 'spoken', 'magic', 'spells.']
Out[5]:
'magic'
In [7]:
new_str.split(" $ ")
Out[7]:
['Money, get away', 'Money, get back', "Money, it's a crime"]

Exercise For The Student

Please refer to the slides, Python help, and the book for an understanding of how the remaining methods work.

In [ ]: