Block B

String Session

String literals can be bounded by single or double quotes.

>>> s = 'single quoted string'
>>> s
'single quoted string'
>>> t = "double quoted string"

Don't do this.

>>> u = "unbalanced string'
  File "<stdin>", line 1
    u = "unbalanced string'
                          ^
SyntaxError: EOL while scanning string literal

Python features zero-based indexing. We start counting at zero.

>>> s
'single quoted string'
>>> s[1]
'i'
>>> s[2]
'n'
>>> s[0]
's'

Slice and dice. This gives us everthing before index 3 in s.

>>> s[:3]
'sin'

Now let's have variable s point at a different string and orphan the old one.

>>> s = "abcdef"

Here we show slicing again.

>>> s[:3]
'abc'

Here is everthing after index 3.

>>> s[3:]
'def'

Guess what's happening here.

>>> s[1:3]
'bc'

This is Skippy. Choosy mothers don't choose it.

>>> s[::2]
'ace'

Let us now capitalize on our good fortune.

>>> s.capitalize()
'Abcdef'
>>> s
'abcdef'

The original string does not change; Python just hands us a copy of the orginal that has been capitalized. Note that Python strings are immutable.

Now we have a variable point at our capitalized string if we want to use it later.

>>> t = s.capitalize()
>>> t
'Abcdef'

Here we orphan the original string with the capitalized one.

>>> s = s.capitalize()
>>> s
'Abcdef'

Now put it back.

>>> s = "abcdef"
>>> s.upper() 'ABCDEF' >>> s = s.upper() >>> s 'ABCDEF' >>> s.lower() 'abcdef' >>> s.swapcase() 'abcdef' >>> s 'ABCDEF' >>> s.swapcase() 'abcdef' >>> s.endswith("f File "<stdin>", line 1 s.endswith("f ^ SyntaxError: EOL while scanning string literal >>> s 'ABCDEF' >>> s.endswith("F") True >>> s.endswith("EF") True >>> s.endswith("DEF") True >>> s.beginswith("ABC") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'str' object has no attribute 'beginswith' >>> s.startswith("ABC") True >>> s.find("q") -1 >>> s 'ABCDEF' >>> s.find("B") 1 >>> test = "abracadabra" >>> test.find("b") 1 >>> test.find("b", 2) 8 >>> test 'abracadabra' >>> test.rfind("b") 8 >>> test.isalnum() True >>> screwy = "#@%$asdfs" >>> screwy.isalnum() False >>> s = "233434" >>> s.isdigit() True >>> q = int(s) >>> q 233434 >>> s = "space cadet" >>> s.isidentifier() False >>> s.isprintable() True >>> s = " cows + File "<stdin>", line 1 s = " cows + ^ SyntaxError: EOL while scanning string literal >>> s = " cows " >>> s.strip() 'cows' >>> s.lstrip() 'cows ' >>> s.rstrip() ' cows' >>> s ' cows ' >>> s = "This is a test of your patience" [Restored Sep 3, 2020 at 11:08:12 AM] Last login: Thu Sep 3 11:08:11 on ttys002 The default interactive shell is now zsh. To update your account to use zsh, please run `chsh -s /bin/zsh`. For more details, please visit https://support.apple.com/kb/HT208050. (base) MAC:Thu Sep 03:11:08:20202021>