Skip to main content
Engineering LibreTexts

9.7: Postlude- Characters Within a String

  • Page ID
    75103
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    These two chapters have dealt with arrays, but let me say a word at this point about strings, and how they can be made to act like arrays in some respects.

    I mentioned earlier in the book that strings, though normally treated as atomic, sometimes tiptoe up to the “atomic/aggregate” line and even cross it. In other words, we will occasionally look at individual parts of a string variable rather than the entire thing as one lump.

    The way we access individual characters within a string is actually the same boxie notation we use for arrays. So this code:

    Code \(\PageIndex{1}\) (Python):

    antihero = "Light Yagami"

    print(antihero[0])

    letter1 = antihero[6]

    letter2 = antihero[7]

    print("{}{}{}".format(letter1,letter2,letter1))

    will give this output:

    | L

    | YaY

    As you can see, string indexes use the same starting-at-zero nonsense that arrays do. Hey, at least it’s consistent.

    This is actually another example of overloading. Just as the len() function means two different things, depending on whether you’re asking for the length of an array or the length of a string, so the boxie notation means two different things. You’re either getting a specific element out of an array, or a specific character out of a string.


    This page titled 9.7: Postlude- Characters Within a String is shared under a not declared license and was authored, remixed, and/or curated by Stephen Davies (allthemath.org) via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?