An important part of programming is working with strings. For this Python is especially suitable, because the handling of strings in Python is very simple.
In this tutorial I would like to show you some of the possibilities Python offers to work with strings.
To get the best learning effect I recommend you to type the examples and not to copy and paste them. This way you can process what you have learned better and retrieve it more easily in later situations.
This is the second part of the introduction to strings in Python. The first part can be found here.
2. Strings in Python
For the examples I use the interactive shell of Python:
$ python3 Python 3.6.8 (default, May 2 2019, 20:40:44) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
We use the following example sentence:
>>> example = "Coding is fun"
In the last section of the previous post we learned how to address single letters of a string. However, if the result is to consist of several letters, we have to use slicing. Such a result is called a substring.
In the following code example we will only return the first word from our example sentence:
>>> example[0:6] # inclusive 0, exclusive 6 'Coding'
In order to obtain the desired result, we must insert in the square brackets the digit of the first position followed by the digit of the last position, separated by
:. The syntax means the following:
Give me the substring of the sentence
examplefrom the position
0inclusive to the position
To illustrate this, let’s look again at what
example return for values:
>>> example 'C' >>> example ' '
As we see,
C as the result and
example returns a space
' '. This should make it clear that the first value
example is inclusive and the last value
example is exclusive. This is also the reason why in the example before (
example[0:6]) we do not get a space as the last value, but the
This behavior is interesting to observe when we type the following:
>>> example[0:0] ''
One could have expected that we would get the first letter returned, similar to indexing, if we had only specified
example = C. However, this is not the case. We get an empty string
The result `example[0:0] = ''` is different from the result `example = ' '`. The first result returns an empty string, whereas the second result returns a space.
Of course, you can also have substrings output in the middle of a sentence during slicing:
>>> example[7:9] 'is' >>> example[4:11] 'ng is f'
It is interesting to know that when slicing the 2nd parameter can also be greater than the number of characters in the sentence. Whereas in indexing, if we have specified a number that is greater than the number of characters in the sentence, we get an index error. However, this is not the case with slicing.
>>> example[3:4543] # the second parameter is much larger than the actual length of the sentence 'ing is fun'
It is sufficient to pass only one digit as parameter during slicing. If, for example, only the second parameter is specified, this means the following:
Output everything from the beginning of the sentence to the digit excluding.
We can output the first word of the sentence in the following way:
>>> example[:6] 'Coding' >>> example[0:6] # inclusive 0, exclusive 6 'Coding'
We can also insert only the first parameter during slicing. Analogous to the other way of writing, this means that we output everything from the parameter to the end of the sentence.
>>> example[7:] 'is fun'
As in Indexing, in Slicing we can also work with negative parameters:
>>> example[-6:] 'is fun'
The last example reads as follows:
Start at the sixth last letter and go to the end of the sentence.
It gets a little more complicated when we work with two negative parameters.
>>> example[-6:-1] 'is fu'
Here we output the substring, starting from the sixth last letter to the penultimate letter.
We can even mix positive and negative parameters when slicing, but you really have to be careful here because this can get complicated very quickly.
>>> example[-6:9] 'is'
In the last example, we let the substring be output from the sixth-last letter to the ninth letter.
However, we must be careful with this example. If we want to go from the sixth last to the fourth letter we get an empty result. This is because the sixth last position is further forward in the string (
example[-6] = 'i', coding is fun) than the fourth position in the string (
example = 'n', coding is fun).
>>> example[-6:4] '' # empty
Of course, we can also work with two negative parameters. However, we have to make sure that the second negative parameter indexes a letter further back in the sentence than the first negative parameter. This is to be considered analogous to the previous example and represents a typical error source.
>>> example[-6:-7] '' # empty >>> example[-6:-4] 'is'
To complete the slicing section here is the table with the indices of the letters. This table helps us to illustrate the indices. It makes slicing easier to understand.
Strings are immutable in Python. This means that once they have been created, they can no longer be modified. This means that if you want to change a string, you have to create a new string. In our example sentence we want to replace the first letter (upper case) with the same letter in lower case.
>>> example = 'c' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment
As we can see, Python won’t let that happen. We get a
TypeError with the hint that the string object in Python does not allow assignment
'str' object does not support item assignment.
So if we want to change a sentence in Python, we have to do it differently. One way to do this is to start a new sentence with a small
c followed by a substring of the example sentence without the first capital letter. In conjunction with string concatenation we come to the following result:
>>> 'c' + example[1:] 'coding is fun'
We could not overwrite the old sentence, but we could easily create a new sentence using the old sentence. We can save the result in a new variable.
>>> fancyexample = 'c' + example[1:] >>> fancyexample 'coding is fun'
In addition, we can use all the functions we’ve learned before to create a new sentence. So of course we can also add a string to the end:
>>> example[:10] + 'really fun' 'Coding is really fun'
We can also exchange one word in the string for another:
>>> example[0:6] + " can be super " + example[10:] 'Coding can be super fun'
So we should keep in mind that strings in Python cannot be changed. However, we can easily use the original string to create new strings.
2.3 Length of a string
In Python, we can use the built-in function
len() to display the length of a string. To do this, we simply pass the name of the variable as a parameter into the function.
>>> len(example) 13
The output confirms that our example sentence has a length of 13 characters.
We can also use the
len() function in conjunction with indexing and slicing:
>>> example[7:len(example)] 'is fun'
In this example we use
len(example) to determine the last digit of the string. We output the substring from index
7 to the end of the sentence (=
However, the example only works because the specification of indexes larger than the number of characters in the string is permitted for slicing. We should also remember that when slicing, a substring is output where the value of the second parameter (corresponds to the position in the string) is exclusive and is therefore not output.
Therefore, you have to be careful in this example, because
len(example) returns the length of the example string (= 13) and not the last index (= 12).
It follows that if we want the last letter of the sentence to be indexed, we must subtract one from the length of our sentence.
>>> example[len(example)-1] 'n'
If we only use the length as an index, we get an index error again:
>>> example[len(example)] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
This is to be expected, since the indices in our example sentence only go from
12. Therefore, in the example
len(example) = 13, we get an index error because the index
13 is not defined in our sentence.
3. Try it out for yourself
You can follow the examples directly here:
If you are using Google Chrome and the widget is not displayed correctly, you must allow third-party cookies or use a different browser.
You should now be able to answer the following questions. These are typical questions that can be asked in exams.
- Why does the following command lead to an error?
example = "Coding is fun" example = 'c'
- How can you output the length of a string?
- How can you output the last letter of a string?
- How can you output the first letter of a string?
- What is indexing?
- What is slicing?
- Do you use single quotation marks or double quotation marks for strings?
- How do you wrap a line in a string?
- How to connect strings?
- How can you output a substring of a string?
In this and in the previous tutorial I introduced strings in Python to you. You now know the basic ways to work with strings and you have learned how to modify strings.
Here we have learned
- What control characters are.
- How you can output multi-line strings.
- How to connect strings together.
- How to output single characters of a string via indexing.
- How to output a substring via slicing.
- How to output the length of a string.
- That strings are immutable.
If you want to read more tutorials, you can find them in my Blog.
Also subscribe to my Newsletter to stay up to date and be the first to know about new entries and videos.
If you have any questions or suggestions, please write me a message or a comment.