Chapter 6 of 15All chapters
Chapter 6 of 15
Strings
Quoting, formatting and slicing text.
Writing them
Single and double quotes are identical in Python, so pick whichever avoids escaping. Triple quotes span lines and are also used for docstrings.
- An f-string interpolates directly: f"Hello {name}, you are {age}".
- Strings are immutable, so every method returns a new string.
Slicing and methods
text[0] is the first character, text[-1] the last, and text[1:4] the characters from index 1 up to but not including 4. The workhorse methods are strip, split, join, replace, lower and startswith.
- ", ".join(items) is the idiomatic way to build a list into a sentence.
- len(text) counts characters, so len("python") is 6.