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
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.
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?
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.
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
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 :
1 2 |
str = "Penjee" print( str[0] ) |
And your console would show a capital P since that’s the first letter of str .
So, if you wanted to print second letter of the string above you could use the code below :
1 2 |
str = "Penjee" print( str[1] ) |
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.
There’s also a very cool shortcut built into python to access the last character in a string by using index -1 :
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.