INTRODUCTION TO STRINGS Review

ok, So im doing the review for strings and it looks like this:


and im curious why you would need an “if, else” statement? wouldn’t slicing the element work just fine without this?

When first introducing strings, it makes very little sense to immediately include a concept as abstract as slicing. It’s important to learn and envision the naive algorithms, and keep that vision, always. It allows us to write more portable code, meaning PORTable, as in porting from one language to another. Slicing is done differently in other languages so it does pay off to use string methods where applicable. All opinion, mind.

so then in this instance when going from the > symbol, that would “port” over to what exactly?
I sort of understand the concept when using something like CSS when using image sizes and animations over to multiple browsers, but does something like the example above behave similarly?

a = "a string"
b = a[2:]

b above makes sense only if we know what a is: a concept, which needs to be understood at a fundamental level. In no particular order, here are some of the properties to investigate:

  • consists of a sequence of characters
  • can be any length, including 0
  • as a sequence it can be indexed
  • as a sequence it is iterable
  • is always delimited (single or double quotes, or triple quoted)
  • is a primitive
  • its characters are Unicode

When recognized as a string primitive, Python gives it virtual instantiation of the str class. It is from this class that strings inherit their methods, including slicing.

>>> isinstance("string", str)
True
>>> 

We didn’t invoke the constructor, the interpreter did, just long enough for it to be type cast as a str object. The primitive still exists in memory. Literals don’t need to be garbage collected, their address in memory is in the source code.

We still haven’t got to the methods, yet. Given the wherewithal suggested above, now we can apply this same technical perspective to another language, say, JavaScript.

const a = "a string";
let b = a.slice(2)

Above we have ported from Python to JavaScript. We now have two program definitions for the same values. Either way, in either language we learn the properties/attributes before the methods.

Of course now there is contradicting information.

console.lof(a instanceof String)    //  false

What the…? JS, unlike Python does not cast primitives to their respective type. It leaves them as primitives but cloaks them (with a wrapper object) so they appear as a ‘string’ type. The primitive is not a String instance like it is in Python.

Bottom line, porting requires a good background in both languages. And good code to begin with, regardless the language. No sense porting over something that does not work, or that is dodgy.

1 Like