Strings

Strings represent text of any kind. As Python needs to distinguish between code (what it should execute) and strings (data), strings have to be wrapped with quotes: single quotes, double quotes, or triple single quotation marks. This last option can be used with multiline text, while the first two options will only work on the same line.

Let's see some examples. Here is a string that is surrounded by single quotes. In this case, you can use double quotes within your text string, and this won't break the parsing mechanism:

text1 = ‘This is a so-called “speakeasy”'

Here is a similar example with double quotes. In this case, we can use single quotes in the text without breaking the code:

text2 = “This is Sam's Tavern”

Finally, triple single quotes allow us to write multiline text:

text3 = ''' This is Sam's Tavern.
"Welcome everyone!" - is written on the door.'''

Another way to enter text that will be multiline in representation is to use a special newline symbol ( ) within your text, on the same line:

>>> print('Hello
World!')
Hello
World!

Strings don't work with most operators. The only exceptions are addition and multiplication. The addition will concatenate two strings, while multiplication (by an integer) will repeat the string:

>>> ‘Hello' + ‘ World!'
'Hello World!'

>>> ‘Hello' * 3
'HelloHelloHello'

However, strings do have multiple built-in methods. Methods are essentially functions that are attached to a particular object, and whose behavior often depends on this object. Methods are defined by the data type or object's class. The following are the most useful methods of strings. The upperlower, and title methods help us to change the casing of the strings:

>>> “Hello World”.upper()
'HELLO WORLD'

>>> “Hello World”.lower()
'hello world'

>>> “hello world”.title()
'Hello World'

Another method, replace, returns the string with the matching values replaced:

>>> “Hello world”.replace(“world”, “planet”)
'Hello planet'

Similarly, the find and rfind methods provide a convenient way to find the index of the first occurrence for the matching string in the initial string. find provides the index starting from the beginning, while rfind finds it from the end:

>>> 'To be or not to be'.find('be') 
3

>>> 'To be or not to be'.rfind('be')
16

Finally, the startswith and endswith methods will return True or False (more on those values later in this chapter) depending on whichever your base string starts or ends with:

>>> 'To be or not to be'.startswith('T')
True

>>> 'To be or not to be'.startswith('t')
False

There also are some other methods that are supported by strings. 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset