Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

The opposite of splitting out string values into a list is joining them, which you do via the join()
function. The join() function allows you to reassemble all the data values in a list back into a
string value.


The join() function is a bit quirky, but it’s extremely versatile, and will come in handy if you have
to manipulate strings.


The join() function uses a single parameter, which is the list or tuple that you want to join into a
string. However, that doesn’t tell the join() function what character to use to separate the different
list values. You need to define a string value that the join() method applies to. To see how this
works, you can take a quick look at the join() function in action. Here are some additional actions
taken on the list1 variable created in the previous example:


Click here to view code image


>>> list1[7] = 'joining'
>>> string10 = ' '.join(list1)
>>> print(string10)
This is a test string used for joining
>>>

This example shows a few different things about strings. First, it replaces the list1 data value at
index 7 with a new word. Then it uses the join() function to reassemble the list back into a string
value. The two single quotes surround a space character, so the join() function adds a space
character between the data values in the list when it creates the string value. Printing the new string
value shows that the list values were reassembled, including the updated value, using the space
character. This is a tricky way to modify words within a text string.


Testing Strings


A vital function in string manipulation is to have the ability to test string values for specific
conditions. Python provides several string-testing functions that help out with that; Table 10.3 shows
them.

Free download pdf