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

(singke) #1

string value. If you want to use the result in your script, you have to assign it to another variable, as in
this example:


Click here to view code image


>>> string7 = 'Rich is working on the problem'
>>> string8 = string7.replace('Rich', 'Christine')
>>> print(string7)
Rich is working on the problem
>>> print(string8)
Christine is working on the problem
>>>

The replace() function changes the string text and returns the result to the string8 variable.
The original string7 value remains the same.


Splitting Strings


Another useful function in string manipulation is the ability to split strings into separate substrings.
This comes in handy when you’re trying to parse string values to look for words. Table 10.2 shows
the Python string-splitting functions that are available.


TABLE 10.2 String-Splitting Functions

If you don’t specify a split character, the split functions use any type of whitespace character as the
split character. In the following example, the result is a list value, with each data value being a
separate word in the original string:


Click here to view code image


>>> string9 = 'This is a test string used for splitting'
>>> list1 = string9.split()
>>> print(list1)
['This', 'is', 'a', 'test', 'string', 'used', 'for', 'splitting']
>>>

This is a great tool for breaking out individual words from a text string for manipulation.


Splitting strings can be somewhat of an art form, and sometimes it takes some experimenting to get it
just right.


Joining Strings

Free download pdf