Introduction to Strings in Python
Tags: python, strings, programming
Published: 2019-01-15 11:51:51

---
title: Introduction to Strings in Python
published: true
description: An introduction to strings in Python
tags: python, strings, programming
---

## Introduction to Strings in Python
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](https://youtu.be/m3U22xrpBF4) for a brief explanation in strings. [String Python Doc](https://docs.python.org/3/library/string.html)

Let's take "Hello, World!" as an example.

|0 | 1| 2| 3| 4| 5| 6| 7| 8| 9|10|11|
|--|--|--|--|--|--|--|--|--|--|--|--|
| H|e |l | l| o| ,| W|o |r | l| d| !|

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[0]
	Out[3]: 'H'
    
	hello[5]
	Out[4]: ','
    
	hello[7]
	Out[5]: 'W'

## Is it In? (No pun intended)
With the help of the "In" operator we can search for characters in a string.

    'W' in hello
    Out[17]: True
    
    'O' in hello
    Out[18]: False

## Index Out of Range

Good so far? Nothing too crazy right? But what happens if we request index 14?

    hello[14]
    Traceback (most recent call last):
    
      File "<ipython-input-7-769cefb1e06b>", line 1, in <module>
        hello[14]
    
    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.

![dir(str)](https://thepracticaldev.s3.amazonaws.com/i/4ucn7ujcg53b4k01cjok.jpeg)

      len(hello)
      Out[26]: 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[13] you'll get another nice index out of range exception, but if you do hello[12] 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](https://docs.python.org/3/tutorial/errors.html)
[Exception Handling Doc](https://docs.python.org/3/library/exceptions.html)

Try the code below, with different index numbers:

```python
    hello = "Hello, World!"
    indexNumber = 11
    try:
        char = hello[indexNumber]
        print(char)
    except ValueError:
        print("Index out of range")
```
## Comparisons
Occasionally you'll want to compare strings for equality
```
    hello == "Hello, World!"
    Out[39]: True
    
    hello == "Hello, world!"
    Out[40]: False
```

## Immutability
Remember I said that strings were immutable? Let's look at the below example:

    
```
    hello[0] = 'g'
    Traceback (most recent call last):
    
      File "<ipython-input-41-2ece3e8e1e48>", line 1, in <module>
        hello[0] = 'g'
    
    TypeError: 'str' object does not support item assignment
```

## Conclusion

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.