Informally, a string is simply some letters in a row.
In Python, strings are enclosed in double quotes. Here are three examples of strings:
"test" "this is a string" "hello world"
Print a string
The code in the code box prints a string. Note that the string
surrounded by quotes.
When you run the program, note that the quotes are not printed. They are not part of the string itself -- they are only there to tell Python that what's in between them is a string.
Run the program to continue.
Conventionally, the first program people write when they try a new language is
one that prints the text
To continue, change the code so that it prints
hello world instead of
Why learn about strings?
Strings are everywhere in most Python programs. For example, strings might be used to represent:
- a user's name, username, or password,
- instructions for the user of your program,
- an error message,
- a link to a site
Strings are one of those fundamentals that, like numbers, you can't really do without when writing larger programs.
Note that strings must be surrounded by quotes. In other words, this program:
and this program:
are different. The first program will give an error if you try to run it. Only the second program will work.
See why quotes matter
Try to change the program in the code box to pretend you forget to put quotes around the
test. You will then get an error message.
Being able to recognize this error message can help you understand why your program doesn't work if you ever forget to put quotes around your strings.
To continue, remove the quotes in the code box and run the program to get an error.
Single quotes work too
Python also allows you to surround a string with single quotes (
than double quotes (
You can use either -- it's a matter of taste. However you cannot mix the two styles in one string.
Being consistent about the style you use will make your programs easier to read, both for yourself and others.
Try using single quotes
Change the program from using double quotes to using single
quotes. The program should still print
hi there to the screen.
You can use the
+ sign to combine two strings into one string. Programmers
call this concatenating two strings.
The program in the code box combines (concatenates) the strings
and prints the result.
Can you guess what the program will print? Run it and see.
Try concatenating strings
Now change the program so that it concatenates (combines) the strings
"gram" to print the word
hologram to the screen.
Things to come
You can do much more with strings. For example, you can:
- extract part of a string (a so-called substring)
- reverse a string
- repeat a string some number of times
- determine the length of a string
However to do these things, you first need to get a firmer grasp of the basics. For example, computing the length of a string requires you to know about function calls, which we'll get to soon.
The things you can do with strings will be covered in a future lesson.