Strings in Python . Beginner’s Guide and Sample Code

Most programming languages have certain types of variables including boolean variables (true or false), numeric variables (integers and/or decimal points). One of the other common types of variables are strings. A string  begins and ends with a quotation mark.  A string in is just  stuff inside quotes.

The sample code below creates 3 different string variables  ( str1 , str2 , and str3 ) and assigns each variable the values you can see below.

Example Code 1

example-code-of-3-strings-in-python

As you can see, you don’t  need to have letters in a string. You can have symbols like the tilde ~  or an asterisk *  or even just a space like the first character of  str3.

space-as-valid-character-in-a-string

So, now that we know how to make a string in Python.

Look at the 4 variables below, can you identify which one(s) are strings?

identify-python-variable-types

The answer:

Only the first two variables are strings! To be a string a variable only needs to do one thing: its value must start and end in quotation marks. That’s it.

identify-python-variable-types-answer

var3 and var4 are not strings. var3 is a boolean and var4 is a floating point variable.  The Python interpreter sees var1 as a string . To Python, var1 just happens to have a capital T as its first character, a lower case r as its second etc..

What if I want to talk about the first character in a string? Or the second character? How do programmers refer to specific places in the string.

Well, we refer to the position of individual characters in the string as its index.

Example Code 2

string-python-indices-labelled

The first character is at index position 0 .  Python is not the only language that starts counting at zero– Many languages start counting do. You’ll get used to it 🙂

So, if you want to print out the first letter of str , you’d write the code :

And your console would show a capital P since that’s the first letter of str .

python-substring-single-letter

 

So, if you wanted to print second letter of the string above you could use the code below :

Since the first letter is at index 0, the second is at index 1 and if you ran the code above you’d see the following output in the console.

console-output-letter-e

There’s also a very cool shortcut built into python to access the last character in a string by using index -1 :

python-string-last-letter-sample-code

In many languages like Java for instance, there’s not an easy way to get the last character in a String, but Python provides this nice convenience method !

So, now that we know how to access any single letter in  a string, let’s explore how to extract multiple letters of a string.