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:
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."""
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:
" ".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.
my_str = " $ " new_str = my_str.join(['Money, get away', 'Money, get back', 'Money, it\'s a crime']) new_str
"Money, get away $ Money, get back $ Money, it's a crime"
A useful opposite of
.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(" $ ")
lyric = "To hear the softly spoken magic spells." parts = lyric.split() print(parts) parts
['To', 'hear', 'the', 'softly', 'spoken', 'magic', 'spells.']
new_str.split(" $ ")
['Money, get away', 'Money, get back', "Money, it's a crime"]
Please refer to the slides, Python help, and the book for an understanding of how the remaining methods work.