liveBook · Manning

String

As explained in Get Programming: Learn to code with Python

A string is a programming-language value representing an ordered sequence of characters or character units as text.

A string is a sequence of characters used as text. In Python, its type is `str`. Put the characters inside matching single or double quotation marks: `"hello"` and `'hello'` are strings. So are `"525600"` (not a number) and `""` (an empty string). Spaces and symbols count as characters too. section 7.1

Want one character? Use an index in square brackets. Counting starts at 0, while `-1` means the last character. For example, `"Python rules!"[0]` gives `'P'`, and `"Python rules!"[-1]` gives `'!'`. A slice uses `[start:stop:step]` to retrieve a substring. section 7.2

Figure 7.1. The string “Python rules!” and the index of each character. The first row shows indexing with positive integers, and the second row shows indexing with negative integers.

Use the two rows of indices to see how the same characters can be counted from the beginning or the end. section 7.2

Once you have a string, try a few small operations:

  • `len("Boston 4 ever")` gives `13`: spaces and symbols are included. section 7.3
  • Use `.lower()` or `.upper()` to change letter case. Use `.find("ing")` to get a substring’s starting index, or `-1` if it is absent. section 7.3 section 8.1
  • `"one" + "two"` gives `'onetwo'`; `3 * "a"` gives `'aaa'`. These operations combine strings or repeat one. section 8.2

Text from a user

`place = input("Where do you live? ")` stores what the user types as a string. `message = place.capitalize() + "!"` then changes its presentation and adds an exclamation mark. If you need a number for arithmetic instead, convert the input first: `num = int(input("Enter a number: "))`. section 11.2

Quick check: Is `"4"` the same type as `4`? No—the quotation marks make the first value a string. To practise further, try finding parts of two names and joining them into a new name. section 7.2 section 12.5

How Get Programming: Learn to code with Python covers it

How deep it goes
Works through literals, indices, slices, methods, concatenation, and repetition, while deferring deeper object-oriented programming.
Examples
Uses quoted digits, indexed characters, essay character counts, repeated hangman dashes, and a name-mashup program.
What it assumes
Builds on variables and basic object types, then teaches string indexing from zero.
What you can do after
Apply it via Python string operations to inspect, change, and combine text for an interactive name mashup.
How it connects
Connects strings to object types, type conversion, substrings, user input, and iteration.

Also explained in

Compare how 24 books explain string →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.