Strings are an essential part of just about any programming language. A string is an array of characters. Is worth noting that strings are immutable in python, meaning you cannot reassign anything to a string already created. If you are a visual learner head over to this link for a brief explanation in strings. String Python Doc
Let's take "Hello, World!" as an example.
In our above example, each letter is assigned to an index. This makes it easy to access anything we want. Try the code below on IDLE or Spyder.
hello = "Hello, World!" hello Out: 'H' hello Out: ',' hello Out: 'W'
With the help of the "In" operator we can search for characters in a string.
'W' in hello Out: True 'O' in hello Out: False
Good so far? Nothing too crazy right? But what happens if we request index 14?
hello Traceback (most recent call last): File "<ipython-input-7-769cefb1e06b>", line 1, in <module> hello IndexError: string index out of range
We get a nice IndexError, we are asking for something that doesn't exist. There are several ways to account for this, but first let's introduce a new built-in function by the way a quick way to know available functions for an object is to call another useful function "dir". Knowing the length of our string could certainly help us to avoid going over the index.
len(hello) Out: 13
If we run len function on our hello string we get the length of our string. Just note that the length doesn't start at 0, it starts at 1. So if you request hello you'll get another nice index out of range exception, but if you do hello you'll get "!". Let's get back to our initial problem of running into IndexError: string index out of range. Handling errors and exceptions is another topic in itself, but we'll briefly show how to prevent it with string indices. If you want to know more about this topic check out this link Error Handling Doc
Exception Handling Doc
Try the code below, with different index numbers:
hello = "Hello, World!" indexNumber = 11 try: char = hello[indexNumber] print(char) except ValueError: print("Index out of range")
Occasionally you'll want to compare strings for equality
hello == "Hello, World!" Out: True hello == "Hello, world!" Out: False
Remember I said that strings were immutable? Let's look at the below example:
hello = 'g' Traceback (most recent call last): File "<ipython-input-41-2ece3e8e1e48>", line 1, in <module> hello = 'g' TypeError: 'str' object does not support item assignment
I really hope you've enjoyed this concise blog about strings. I'll be writing a few other blogs about other useful string methods. Any errors or feedback please comment below.