This tutorial will teach you about the string data-type in Python.
- Know basics of Python 3 if not read here
- Knowledge of Computer Science data-structures will help
What are they?
A string data-type in Python allows us to store a sequence of characters. Strings are a immutable type meaning they can’t be modified after it has been defined. We can however replace the whole string with another one. Strings in Python are also indexed, which allows us to access them as if they were a list.
Every index of a string is one character.
Unlike other programming languages there is no “char” type to store a singular character.
Modifying a strings data requires the reference the object to be redefined.
Defining a String in python is quite simple, you just need to wrap what you want as a string into double quotes.
When the code is run you should get
Hello World! output to your terminal.
When we want to access a String’s content, there are several ways we can achieve this. We can get all content, a single index (character), or we can use what is “slicing”.
Accessing the whole content was shown when creating the String in the previous example, when we output the string to the console.
Accessing a single character by index is the same as when using a list.
When this code is run you should see the character
Remember indexes in Python start at 0
A white-space counts as a character and therefore has an index
We can use the same slice operation from the list data-structure.
When this code is run you should see the word
When slicing [0:x] and [:x] mean the same thing
Remember we can’t modify a string’s data directly, as it must be redefined. So changing a character through it’s index or appending/inserting methods will not work.
We can however use concatenation. Which was covered in a previous tutorial here.
In this code example I am using slicing the select the
Hello part. Then it is concatenating the word
Leo, then storing it back into the named variable “my_first_str”. When run you should see the following output:
Like most other data-types in Python, strings have lot’s of extra features that can be used. I will show you some of them.
||Makes a string uppercase|
||Makes a string lowercase|
||Reverses the string backward|
There is also special characters you can place in a string. You can achieve this using the backslash character, because of this if you want to use the backslash as a character you will have to place multiple.
Here is some of the notations you can use:
||Single quote character|
||Double quote character|
There are many more things you can do with strings. One of them is string formatting, you can read about that here.