The string type - interactive - SOLVED#

A string is made by enclosing something in quotes. Here are three different ways of making a string. All are allowed, and you’ll see all of them.

string1 = 'strng1'
string2 = "strng2"
string3 = """strng3""" # Triple quotes

The first two are common with short strings. If you want a long string that spans several lines, or that contains quotes in it, you can enclose it in triple quotes.

EXERCISES Now let’s try some operations on strings. For each, think about what you expect, remembering that Python should try to do the most sensible thing if it can.

  1. Can you add two strings?

  2. Can you add a number to a string?

  3. Can you multiply two strings?

  4. Can you multiply a string by an integer?

  5. If two strings have the same content, what happens if I do string1 == string2

  6. What happens if you do string1 > string2? Try with some test examples to figure out what’s going on. Discuss with us!

string1 + string2
'strng1strng2'
string1 + 2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [3], in <module>
----> 1 string1 + 2

TypeError: can only concatenate str (not "int") to str
string1 * string2
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [4], in <module>
----> 1 string1 * string2

TypeError: can't multiply sequence by non-int of type 'str'
string1 * 3
'strng1strng1strng1'
string1 == string2
False
string1 > string3
False
'book' > 'boot'
False