Python for Beginners

Introduction to Strings I

Last updated on August 19, 2019 by Michael Lossagk , 12 min  • 
Introduction to Strings I

1. Introduction


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.

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.
>>>

2.1 Introduction to Strings


In Python, strings are placed in single ' ('I am a string') or double quotes " ("I am a string").

# double quotes
>>> print("Hello World")
Hello World

# simple quotes
>>> print('Hello World')
Hello World

# Mixed quotation marks lead to an error
>>> print('Hello World")
  File "<stdin>", line 1
    print('Hello World")
                       ^
SyntaxError: EOL while scanning string literal

2.2 Control Character


Now maybe one of you is wondering how you can use a quotation mark inside strings to write the following: He said: "Python is cool.". There is a solution for this, too. If you want to prevent control characters from being interpreted as such in programming languages, you can use so-called escape characters also escape sequences. In Python we use the backslash \ which we prefix with the quotation mark inside the string:

# escape character
>>> print("He said: \"Python is cool.\"")
He said, "Python is cool."

If you put a string in single quotation marks, you can use double quotation marks within the string without escape sequence.

>>> print('He thinks, "Learning to program can be easy."')
He thinks, "Learning to program can be easy."

Another important escape sequence is \n. We use this escape sequence to create a text break and continue the string in a new line. This is important to note, otherwise it can lead to problems as we will see in the following example.

>>> print("'C:\a\new\path'")
'C:\a
ew\path'

As we can see, the text was wrapped by the control character \n, but this is not the result we wanted to achieve. To prevent this, we have to place a control character \ before the escape sequence \n. Colloquially one also says: we escape nwith a \.

>>> print("'C:\a\\new\path'")
'C:\a\new\path'

Another control character in Python is \t. We can use it to create a tab spacing.

>>> print("After this text comes a tab spacing \t Before this, text comes a tab spacing.")
After this text comes a tab spacing   Before this, text comes a tab spacing.
>>> print("Tab, Tab, Tab \t\t\t The distance is now greater.")
Tab, Tab, Tab 			 The distance is now greater..

2.3 Multiline Strings


Strings can extend over several lines. In Python you can use the triple quotes for this, either in double """"..."""" or in single '''...''' quotation marks.

>>> print("""
... This is a
... long sentence with
... Line breaks.
... """)
# this is a blank line
This is a
long sentence with
Line breaks.

Line ends are automatically included in the string, such as the empty line between the end of the print() function and the beginning of the output. But it is possible to prevent this by appending a \ to the end of the line. This is illustrated by the following example:

>>> print("""\
... In this example
... the first line is
... not broken.
... """)
In this example # here is no blank line between the print() function and the output
the first line is
not broken.

Here we have no blank line between the end of the print() command and the output.

2.4 Strings and concatenation


In Python strings can be linked together with the plus sign +.

>>> "That is a" + " whole sentence."
'That is a whole sentence.'

Strings in Python can be multiplied with the multiplication sign *. This can also be combined with concatenation.

>>> 3 * "Hello, " + "is anyone there?"
'Hello, Hello, Hello, is anyone there?'

Of course, concatenation and multiplication of strings can also be used in connection with variables.

>>> hello = "Hello, "
>>> at_home = "is anyone there?"
>>> 3 * hello + at_home
'Hello, Hello, Hello, is anyone there?'
>>> 3 * hello + "does anyone hear me?"
'Hello, Hello, Hello, does anyone hear me?'

2.5 Stringindexing


Strings can be indexed, whereby the first character has the index 0.

>>> example = "Coding is fun"
>>> example[0]
'C'

By writing example[0] we access the first letter of the sentence. The reason why the first letter starts with the number 0 and not 1 is of historical origin. Python is a so-called “higher” programming language and such programming languages are based on machine-oriented programming languages like C or Assembler. The origin is to be found in these languages and goes beyond the topic of this tutorial.

However, this behavior is common for most programming languages and you should keep it in mind and get used to it. I emphasize this here and attach great importance to addressing it, as it is a typical error source in programming, and not only for beginners.

Indexing also works with any other letter in the sentence, depending on which number is passed as a parameter.

>>> example[4]
'n'
>>> example[6]
' '
>>> example[7]
'i'
>>> example[9]
' '
>>> example[10]
'f'
>>> example[12]
'n' # last string in sentence

Now the question arises what happens when we choose a number that is greater than the number of letters in that sentence?

>>> example[13]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

As we can see this is not possible in Python and leads to an error. We get an IndexError which tells us that the string to be indexed does not have so many digits and the access with index 13 is not valid.

It is therefore not possible to select an index that is larger than the number of the characters in the sentence. However, in Python it is possible to choose a negative index, as the following example shows:

>>> example[-1]
'n'

The index -1 corresponds to the last letter of the sentence. So if we work with negative indices, then “we run the sentence from back to front”.

The sentence in our example has exactly 13 characters (including spaces). So if we choose the index -13, we arrive again at the very first character of the sentence.

>>> example[-13]
'C'
>>> example[-12]
'o'
>>> example[-11]
'd'
>>> example[-10]
'i'
>>> example[-9]
'n'
>>> example[-8]
'g'

As with the use of positive indices, we must be careful with negative indices. We can not choose an index that is larger than the number of characters the sentence. This means, for example, that if we select the index -14, we get displayed an IndexError again:

>>> example[-14]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

If you have paid close attention, you will have noticed that we can address the last letter of the sentence with the index 12 for positive indices (example[12] = 'n') and with negative indices the last letter of the sentence (seen from behind) with the index -13 (example[-13] = 'C'). The reason for this is that for positive indices we start with index 0 to get the first letter and for negative indices we start with index -1 to get the first letter seen from behind.

In other words: We don’t start at index -0, because -0 = 0, so we have to start at index -1 to make the expression unique for Python.

This must be taken into account when indexing, as this is a frequent source of errors.

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.

4. Typical exam questions


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[0] = 'c'
  • How can one output the last letter of a string?
  • How can one output the first letter of a string?
  • What is indexing?
  • Do you use single quotation marks or double quotation marks for strings?
  • How do we wrap a line in a string?
  • How do we connect strings?

5. Summary


In this tutorial I introduced you to strings in Python. 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

Code examples for Python can be found in my GitLab repository and at repl.it. If you want to know more about Python and programming, I can recommend this book.

If you liked the post, then I would be happy if you subscribe to my YouTube Channel and Instagram.

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, write me a message or a comment.


Michael Lossagk
Michael Lossagk
Coding Enthusiast
Founder @ TechDiffuse

You may also like


Share this: