Skip to main content
Engineering LibreTexts

6: Strings

  • Page ID
    122350
  • \( \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}}\)

    \( \newcommand{\vectorA}[1]{\vec{#1}}      % arrow\)

    \( \newcommand{\vectorAt}[1]{\vec{\text{#1}}}      % arrow\)

    \( \newcommand{\vectorB}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vectorC}[1]{\textbf{#1}} \)

    \( \newcommand{\vectorD}[1]{\overrightarrow{#1}} \)

    \( \newcommand{\vectorDt}[1]{\overrightarrow{\text{#1}}} \)

    \( \newcommand{\vectE}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash{\mathbf {#1}}}} \)

    \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \)

    \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)

    \(\newcommand{\avec}{\mathbf a}\) \(\newcommand{\bvec}{\mathbf b}\) \(\newcommand{\cvec}{\mathbf c}\) \(\newcommand{\dvec}{\mathbf d}\) \(\newcommand{\dtil}{\widetilde{\mathbf d}}\) \(\newcommand{\evec}{\mathbf e}\) \(\newcommand{\fvec}{\mathbf f}\) \(\newcommand{\nvec}{\mathbf n}\) \(\newcommand{\pvec}{\mathbf p}\) \(\newcommand{\qvec}{\mathbf q}\) \(\newcommand{\svec}{\mathbf s}\) \(\newcommand{\tvec}{\mathbf t}\) \(\newcommand{\uvec}{\mathbf u}\) \(\newcommand{\vvec}{\mathbf v}\) \(\newcommand{\wvec}{\mathbf w}\) \(\newcommand{\xvec}{\mathbf x}\) \(\newcommand{\yvec}{\mathbf y}\) \(\newcommand{\zvec}{\mathbf z}\) \(\newcommand{\rvec}{\mathbf r}\) \(\newcommand{\mvec}{\mathbf m}\) \(\newcommand{\zerovec}{\mathbf 0}\) \(\newcommand{\onevec}{\mathbf 1}\) \(\newcommand{\real}{\mathbb R}\) \(\newcommand{\twovec}[2]{\left[\begin{array}{r}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\ctwovec}[2]{\left[\begin{array}{c}#1 \\ #2 \end{array}\right]}\) \(\newcommand{\threevec}[3]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\cthreevec}[3]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \end{array}\right]}\) \(\newcommand{\fourvec}[4]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\cfourvec}[4]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \end{array}\right]}\) \(\newcommand{\fivevec}[5]{\left[\begin{array}{r}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\cfivevec}[5]{\left[\begin{array}{c}#1 \\ #2 \\ #3 \\ #4 \\ #5 \\ \end{array}\right]}\) \(\newcommand{\mattwo}[4]{\left[\begin{array}{rr}#1 \amp #2 \\ #3 \amp #4 \\ \end{array}\right]}\) \(\newcommand{\laspan}[1]{\text{Span}\{#1\}}\) \(\newcommand{\bcal}{\cal B}\) \(\newcommand{\ccal}{\cal C}\) \(\newcommand{\scal}{\cal S}\) \(\newcommand{\wcal}{\cal W}\) \(\newcommand{\ecal}{\cal E}\) \(\newcommand{\coords}[2]{\left\{#1\right\}_{#2}}\) \(\newcommand{\gray}[1]{\color{gray}{#1}}\) \(\newcommand{\lgray}[1]{\color{lightgray}{#1}}\) \(\newcommand{\rank}{\operatorname{rank}}\) \(\newcommand{\row}{\text{Row}}\) \(\newcommand{\col}{\text{Col}}\) \(\renewcommand{\row}{\text{Row}}\) \(\newcommand{\nul}{\text{Nul}}\) \(\newcommand{\var}{\text{Var}}\) \(\newcommand{\corr}{\text{corr}}\) \(\newcommand{\len}[1]{\left|#1\right|}\) \(\newcommand{\bbar}{\overline{\bvec}}\) \(\newcommand{\bhat}{\widehat{\bvec}}\) \(\newcommand{\bperp}{\bvec^\perp}\) \(\newcommand{\xhat}{\widehat{\xvec}}\) \(\newcommand{\vhat}{\widehat{\vvec}}\) \(\newcommand{\uhat}{\widehat{\uvec}}\) \(\newcommand{\what}{\widehat{\wvec}}\) \(\newcommand{\Sighat}{\widehat{\Sigma}}\) \(\newcommand{\lt}{<}\) \(\newcommand{\gt}{>}\) \(\newcommand{\amp}{&}\) \(\definecolor{fillinmathshade}{gray}{0.9}\)

    • 6.1: A string is a sequence
      This page explains that a string is a character sequence indexed by brackets, following zero-based indexing in Python. Each character can be accessed using its index, starting from 0. It notes that any expression resolving to an integer can be an index, while non-integer indexes, like floats, will produce a TypeError.
    • 6.2: Getting the length of a string using len
      This page explains how to measure string length using `len`, exemplified with 'banana'. It highlights the mistake of using an out-of-range index to access the last character and corrects it by showing the need to subtract one from the length. Furthermore, it introduces negative indices, which allow direct access to characters from the string's end, like using `fruit[-1]` for the last character.
    • 6.3: Traversal through a string with a loop
      This page discusses string traversal, explaining how to process strings character by character. It includes an example of using a while loop to print each character of 'fruit' line by line, stopping when the index reaches the string length. An exercise is suggested to reverse this traversal. Additionally, the page introduces a for loop as another method for iterating through strings until completion.
    • 6.4: String Slices
      This page explains string slicing in Python, which selects a portion of a string using indices. A slice includes characters from the starting index up to, but not including, the ending index. Omitting the starting index begins the slice at the start of the string, while omitting the ending index slices to the end. If the starting index equals or exceeds the ending index, it returns an empty string. It also raises a question about the outcome of slicing a string with fruit[:].
    • 6.5: Strings are immutable
      This page explains the immutability of strings in Python, noting that individual characters cannot be changed without causing a TypeError. Instead, it suggests creating new strings through concatenation and slicing. An example provided illustrates this concept by showing how to change 'Hello, world!' to 'Jello, world!' while keeping the original string intact.
    • 6.6: Looping and Counting
      This page explains a program that counts the occurrences of the letter 'a' in the string "banana" using a loop and a counter. It initializes the count to 0 and increments it for each 'a' found, ultimately printing the count. There’s a suggestion to improve the program by encapsulating the code in a function called 'count', which would take the string and the letter to count as parameters.
    • 6.7: The in operator
      This page explains the boolean operator "in," which checks if one string is a substring of another, returning True or False based on its presence. Examples demonstrate that 'a' is found in 'banana' (True), while 'seed' is not present (False).
    • 6.8: String Comparison
      This page explains how Python's comparison operators function with strings, highlighting equality checks and alphabetical ordering. It notes that uppercase letters come before lowercase ones, and recommends converting strings to a uniform case, such as all lowercase, for consistent comparisons.
    • 6.9: String Methods
      This page outlines the nature of strings as Python objects that encompass data and methods. It covers how to utilize `dir` and `type` functions to examine string methods, emphasizes the distinction between calling methods and functions, and provides examples of methods like `find`, `strip`, and `startswith`. The text concludes with an exercise on the `count` method, urging readers to delve into the documentation for deeper comprehension.
    • 6.10: Parsing strings
      This page provides a guide on extracting a substring from an email address using Python string methods. It details how to locate the "@" symbol and the subsequent space to slice the string for the domain part (e.g., "uct.ac.za"). The process involves using the `find` method to identify character positions for slicing. Documentation for the `find` method is also referenced.
    • 6.11: Format operator
      This page explains the use of the format operator (%) in Python for string formatting, which replaces parts of a string with variable data. While it functions as a modulus operator for integers, it formats strings with specific sequences (e.g., "%d" for integers, "%g" for floats). Using multiple sequences requires a tuple, and it’s crucial to match the number and type of elements to avoid TypeErrors. Despite its capabilities, the format operator can be difficult to master.
    • 6.12: Debugging
      This page highlights the importance of handling user errors in programming, particularly through a demonstration of a while loop that fails with empty input, causing an IndexError. It suggests using the startswith method or the guardian pattern to manage empty strings, thereby enhancing the robustness of the code against such input errors.
    • 6.E: Strings (Exercises)
      This page discusses Python string manipulation exercises. Exercise 5 focuses on extracting a numeric value from a string using techniques like find and slicing, converting it to a float. Exercise 6 encourages exploring string methods from the official documentation, emphasizing 'strip' and 'replace', and explains the syntax of optional arguments and tuples, with further details to be addressed in a subsequent chapter.
    • 6.G: Strings (Glossary)
      This page defines programming concepts including variables (counters, flags, objects), string-related terms (empty strings, format strings, operations), and sequences (items, indices, slices, traversal methods). It also covers methods for objects and highlights the immutability of certain sequences.


    This page titled 6: Strings is shared under a CC BY 4.0 license and was authored, remixed, and/or curated by Chuck Severance via source content that was edited to the style and standards of the LibreTexts platform.