In this lesson, we are going to learn about strings. You might think that you already know everything about them, but this is certainly not true. So far, we know that input is automatically converted into strings if we don’t indicate otherwise and that we need to use quotation marks if we want to print strings. Maybe you even remember that to convert another data type into string, you can use the function str().
But there is much more we can do and it is important to know it, as strings are the data type to represent human language, so you are likely to get lots of input in this format and of course you are going to want to work with it. So read carefully the theory to be able to solve the mini-exercise at the end. Besides learning about strings, this lesson teaches you operations that are not only valid for strings, but also for other kinds of sequence-based data types. We are going to learn more about them in the next lesson.
Operations for sequence-based data types
- built-in function len():returns the length of a sequence, i.e. the number of characters in a string or, more generally speaking, the number of elements in a sequence
- the + operator to concatenate sequences: creates a new sequence by combining others
- the * operator to repeat a sequence a given number of times
- bracket operator to index an element: You can access individual elements using the index. An index is the number of the position of the element in a sequence.
- To access it, you write the number of the position in square brackets [] after the list’s name.
- You count the position starting from 0 for the first element – just like the range() function. For example, to access the fifth element, you write list_name[4].
- The index needs to be an integer, but you can define it using numbers and variables.
- You can also use negative indices. They will start counting from the end, for instance, the index -1 will show you the last element.
- slice operator to select a segment of a string, i.e. a range of elements:
- Just like when you access or select a character, you indicate the position of the first element you want to include and connect it with a colon to the position of the element after the last one that you want to include. Again, this is just like using the range() function.
Example: myString[4:7] returns the part of the string called myString from the fifth character to the seventh character. You might think that this contradicts what I just explained (including the first, but excluding the last element), but remember that this is due to the way we count in programming, i.e. starting from 0. - If the first index is greater than or equal to the second the result is an empty string.
- If you leave blank either the beginning or the end of the slice operator, Python replaces the missing value either by the first or the last position, respectively. Thus, if you leave blank both of them (string_name[:]), you get the whole string.
- Just like when you access or select a character, you indicate the position of the first element you want to include and connect it with a colon to the position of the element after the last one that you want to include. Again, this is just like using the range() function.
- relational operators to compare two sequences: bigger (>), smaller (<) and equal (==) allow for comparisons and Python will return either a True or a False as a result.
For sequences, the response is only True if it is true for all elements included in the comparison. For instance (0, 1, 2) < (1, 3, 4) would be True.
For strings, bigger and smaller refers to the position of the word in the alphabet. A word that is considered “bigger” comes later in the alphabetical order. However, you need to be careful, as Python puts all the uppercase letters before all the lowercase letters. - traversal (= processing a sequence one element at a time): Using a for or a while loop, a program starts from some point, selects each character in turn, does something to it, and continues until the end. This can be very useful, for instance if you want to count something and or spell a string.
Particularities of strings
- immutable: You cannot change a string. Nevertheless, you can replace it with a string with the same name that contains the changed element. Basically, you cannot use the index operator to change an element, but you can construct a new string (even with the same name) using the slice operator. For instance, writing word = word[0:2] + “z” + word[3:] replaces the current position 2 (third letter) with a z.
- string methods: For strings, you have the possibility to use in-built methods, similar to functions. Their syntax is different from functions, though: You write the name of your string followed by a point and then the name of the method ending with round brackets (). If the method requires additional information, you enter it as an argument in the brackets. With functions, we say that we are calling them and for methods, we are invoking the method on the string.
Examples:- string_name.isupper(): returns true if all letters of the string are uppercase letters
- string_name.upper() or string_name.capitalize(): converts all letters of the string into uppercase letters
- string_name.find(‘letter’): searches for the letter or substring that you put as the first argument (needs to be inside single quotation marks) and returns the position where it (first) appears (additionally, you can determine the beginning and/or the end of the search by entering it as the second or third argument, respectively)
- string1 in string2: The word in is a boolean operator that takes two strings and returns True if string1 appears as a substring in string2. You can also use this to define a function that tells you which letters appear in both strings.
Mini-Exercise: Ask your user to give you a random word.
- What are two ways you could print ONLY the last letter of the word?
- How would you print all letters (one per line)?
- Count how many times a certain letter appears in the word.
- Search a string for a particular letter: In which position does it appear for the first time? Find two ways to do it.
- Bonus question: How could you reverse the letters, i.e. print the word starting with the last one (example: small → llams)? Hint: you can use this formula t = s[∷-1].
Your solution might look like this:


For more details and longer explanations you can look at Allen B. Downey’s Think Python, which also inspired this post. #mastery18