# Intro to Python ## Week 6 ### Strings --- ## While you wait #### Open these URLs: - [NLPiA.org/fall26](https://NLPiA.org/fall26) - [GitLab.com/mesa_python/fall26](https://GitLab.com/mesa_python/fall26) - [Runestone.Academy](https://Runestone.Academy) --- ## Primitive Types - How many primitive types are there? - Can you list the primitive types? - What is the simplest primitive type? - More complicated == more memory (RAM) - More complicated == more possible values note: - Trying to give you a mental model of what is happening inside your computer - What you can use them for - How big they are in RAM --- ## Primitive Types - bool - int - float - str --- ## 6 ``type``s you know 1. `NoneType` 2. `bool` 3. `int` 4. `float` 5. `str` 6. `list` --- ## 4 ``types`` you'll soon know 7. `bytes` 8. `tuple` 9. `set` 10. `dict` --- ## Why `None`? - need something for nothing - not an empty string - not `float('nan')` - not `1 / float('inf')` --- ## Why an object for nothing You can't accidentally create multiple `None`s ```python >>> None == None True >>> None is None True >>> id(None) == id(None) True ``` --- ## Less RAM A _Singleton_ has only 1 address/location in RAM ```python >>> type(None) NoneType >>> NewNoneType = type(None) >>> new_none = NewNoneType() >>> new_none NoneType ``` --- ## Can't create a new ```python >>> new_none = NewNoneType() >>> id(new_none) 21290576 >>> id(None) 21290576 >>> id(None) == 21_290_576 True ``` ## Reasons for `None` - something for `print` to `return` - default `return` value for all functions ```python >>> import json >>> javascript_none = json.loads('null') >>> print(javascript_none) None >>> id(javascript_none) 21290576 ``` note: - same `id` as before, no matter how you create it --- ## Zero - 200 BC - Chandah-sutra of Pingala "śūnya" - ? BC - Egyptian [](wk6/hiero_F35.png) - ? BC - Mayan 𝋠 - ? AD - Arabic "ṣafira" ٠ - 1000 AD - Greek "Zephyrss" (west wind) - 1170 AD - Italian "zefiro" - 1200 AD - Venetian "zevero" - 1300 AD - French "zéro" - 1598 English "zero" --- [](wk6/hiero_F35.png) --- [](wk6/Cero_maya.svg.webp) --- ## Grouping symbols - `()` - `[]` - `{}` --- ## f-strings ```python >>> name = 'Prof' >>> greeting = f'Hello {name}' >>> greeting ``` --- ## f-strings ```python >>> name = 'Prof' >>> greeting = f'Hello {name}' >>> greeting 'Hello Prof' ``` --- ## Primitive Types ```python >>> type(True) >>> type(1_000) >>> type(1.0) >>> type("1.0") >>> type(None) ``` note: - Here are the primitive or simple types you've learned about so far --- ## Primitive Types ```python >>> type(True) bool >>> type(1_000) >>> type(1.0) >>> type("1.0") >>> type(None) ``` --- ## Primitive Types ```python >>> type(True) bool >>> type(1_000) int >>> type(1.0) >>> type("1.0") >>> type(None) ``` --- ## Primitive Types ```python >>> type(True) bool >>> type(1_000) int >>> type(1.0) float >>> type("1.0") >>> type(None) ``` --- ## Primitive Types ```python >>> type(True) bool >>> type(1_000) int >>> type(1.0) float >>> type("1.0") str >>> type(None) ``` --- ## Primitive Types ```python >>> type(True) bool >>> type(1_000) int >>> type(1.0) float >>> type("1.0") str >>> type(None) NoneType ``` --- ## Types - `NoneType` - `bool` - `int` - `float` - `str` - `list` - `tuple` - `dict` - `set` --- ## Grouping symbols You can think of these symbols as quotes, for collections: - `()` - `[]` - `{}` --- ## f-strings ``` >>> name = 'Prof' >>> greeting = f'Hello {name}' >>> greeting ``` --- ## f-strings ``` >>> name = 'Prof' >>> greeting = f'Hello {name}' >>> greeting 'Hello Prof' ``` --- ## Raw strings Raw strings are for strings with backslashes ```python >>> r'ABC' == 'ABC' True >>> r'A\tB\tC' == 'A\tB\tC' False >>> r'C\path\to\file.py' 'C\\path\\to\\file.py' ``` note: - raw strings are for backslashes in code `str`s: - backslashes in regular expressions - backslashes in doctests - backslashes in Microslop pathsremember how we use `\n` for newline characters in Python? - code (like Microslop paths and regexes) contain backslashes --- ## Doctests Without that `r` this `doctest` will fail and raise an `Exception` ```python r""" >>> s = 'A\tB\tC' 'A\\tB\\tC' """ ``` --- ## Active practice - [nlpia.org/fall26/wk6/active_practice.py](wk6/active_practice.py) - [nlpia.org/fall26/wk6/practice_doctest_pairs.txt](wk6/practice_doctest_pairs.txt) - Optional (advanced): [nlpia.org/fall26/wk6/edit_distance.py](wk6/edit_distance.py) --- ## Regular expressions A regex is code that uses backslashes a lot: ```python >>> import re >>> re.split(r'\d', 'A1B2C') ['A', 'B', 'C'] >>> re.findall(r'\d', 'A1B2C') ['1', '2'] >>> re.findall(r'\d+', 'A10B20C') ['10', '20'] ``` note: - regexes are usually used for search & replace on text - check out your `.*` button in Sublime - regexes are great for splitting (tokenizing) text - because you can rejoin the tokens back into text --- ## Advanced `re` (regular expressions) ```python >>> re.match(r'A\d+B\d+C', 'A10B20C')
>>> re.finditer(r'\d+', 'A10B20C')
>>> list(re.finditer(r'\d+', 'A10B20C')) [
,
] ``` note: - regexes are useful for code - exact pattern matches - parsing - interpretting - natural language - parsing (`spacy`) - tokenizing - detokenizing (rejoining) --- ## Byte ``str``ings Byte strings (`bytes()`) are for binary strings ```python >>> b'ABC' == bytes('ABC') True >>> bytes('ABC') b'ABC' >>> 'ABC'.encode() b'ABC' >>> str(b'ABC') 'ABC' ``` note: - `str()` on `bytes` is same as `bytes.decode` - `bytes()` on `str` is same as ``str.encode` ## Unicode - Unicode `str`s abstract away unicode complexity - Unicode `str`s just look prettier ```python >>> 'Résumé'.encode() b'R\xc3\xa9sum\xc3\xa9' >>> b'R\xc3\xa9sum\xc3\xa9'.decode() 'Résumé' ``` note: - you cannot use `str` to convert bytes to str --- ## Unicode - ASCII (7 bits) has 128 possiblities - `str`ings are multibyte characters - Unicode has millions of characters ```python >>> len('😀') 1 >>> len(b'\xf0\x9f\x98\x80') 4 >>> len('é') 1 >>> len('\xc3\xa9') 2 ``` --- ## Quotes - `"""a very long string literal"""` - `"a string literal"` - `'a string literal'` --- ## Quotes - `"""a very long string literal"""` - `"a string literal"` - `'a string literal'` --- ```python >>> 'Python'[1] ``` --- ```python >>> 'Python'[1] 'y' ``` --- ```python >>> 'Python'[0] ``` --- ```python >>> 'Python'[0] 'P' ``` --- ```python >>> 'Python'[-1] ``` --- ```python >>> 'Python'[-1] 'n' ``` --- ```python >>> 'lane.py'[4] ``` --- ```python >>> 'lane.py'[4] '.' ``` --- ```python >>> 'lane.py'[0:4] ``` --- ```python >>> 'lane.py'[0:4] 'lane' ``` --- ```python >>> 'lane.py'[:4] ``` --- ```python >>> 'lane.py'[:4] 'lane' ``` --- ```python >>> 'lane.py'[-1] ``` --- ```python >>> 'lane.py'[-1] 'y' ``` --- ```python >>> 'lane.py'[-3] ``` --- ```python >>> 'lane.py'[-3] '.' ``` --- ```python >>> 'What is the fourth character here?'[5] ``` --- ```python >>> 'What is the fourth character here?'[5] ' ' ``` --- ```python >>> 'What is the last character?'[-1] ``` --- ```python >>> 'What is the last character?'[-1] '?' ``` --- ```python >>> '"First character?"'[0] ``` --- ```python >>> '"First character?"'[0] '"' ``` --- ```python >>> '"First and last equal?"'.strip('"')[0] ``` --- ```python >>> '"First and last equal?"'.strip('"')[0] 'F' ``` --- ```python >>> '"First character?'[0] ``` --- ```python >>> '"First character?'[0] '"' ``` --- ```python >>> 'Strings are sequences of characters.'[5] ``` --- ```python >>> 'Strings are sequences of characters.'[5] 'g' ``` --- ```python >>> len('wonderful') ``` --- ```python >>> len('wonderful') 9 ``` --- ```python >>> 'Mystery'[:4] ``` --- ```python >>> 'Mystery'[:4] 'Myst' ``` --- ```python >>> 'M' in 'Mystery' ``` --- ```python >>> 'M' in 'Mystery' True ``` --- ```python >>> 'a' in 'Apple' ``` --- ```python >>> 'a' in 'Apple' False ``` --- ```python >>> 'p' in 'Pineapple' ``` --- ```python >>> 'p' in 'Pineapple' True ``` --- ```python >>> 'apple' in 'Pineapple' ``` --- ```python >>> 'apple' in 'Pineapple' True ``` --- ```python >>> 'pear' not in 'Pineapple' ``` --- ```python >>> 'pear' not in 'Pineapple' True ``` --- ```python >>> 'apple' > 'pineapple' ``` --- ```python >>> 'apple' > 'pineapple' False ``` --- ```python >>> 'pineapple' < 'Peach' ``` --- ```python >>> 'pineapple' < 'Peach' False ``` ---