place three single or double quotes in a row to define the end of the string, as shown in this example:
Click here to view code image
>>> string5 = '''This is another long string
value that will span multiple
lines in the output'''
>>> print(string5)
This is another long string
value that will span multiple
lines in the output
>>>
Notice though that with the triple-quotes method, the string value preserves any newlines that are
added to the text. This can come in handy if you need to store text that has embedded newline
characters that you want to display.
Handling String Values
After you assign a string value to a variable, you can use the value as a whole, or you can work with
parts of the string value.
As you’ve seen from the print() examples so far, to reference the whole string value, you just
reference the string by specifying the variable name. You can also retrieve a subset of the string text
stored in the variable by using a few different Python techniques.
Python treats string values somewhat like tuple values (see Hour 8, “Lists and Tuples”). You can
reference an individual character in a string by using an index value, as shown here:
Click here to view code image
>>> string6 = 'This is a test string'
>>> print(string6[5])
i
>>>
However, as with tuples, Python won’t let you change an individual character in the string by using
the index. Here’s an example:
Click here to view code image
>>> string6[5] = 'a'
Traceback (most recent call last):
File "<pyshell#16>", line 1, in <module>
string6[5] = 'a'
TypeError: 'str' object does not support item assignment
>>>
Also very much like with tuples, you can use slicing to retrieve a larger subset of characters from a
string. Here’s how:
>>> print(string6[5:7])
is
>>>
Slicing is a powerful tool to have when you’re trying to extract specific data from string values, such
as if you’re trying to scrape data values from a webpage’s content. Besides slicing, Python also
supports lots of string functions to help you manipulate string values for just about every application.
The next section takes a look at some of the most useful string functions that you’ll run into as you