DEV Community

Fernando B πŸš€
Fernando B πŸš€

Posted on

Introduction to Strings in Python

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 for a brief explanation in strings. String Python Doc

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'
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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)

  len(hello)
  Out[26]: 13
Enter fullscreen mode Exit fullscreen mode

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
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")
Enter fullscreen mode Exit fullscreen mode

Comparisons

Occasionally you'll want to compare strings for equality

    hello == "Hello, World!"
    Out[39]: True

    hello == "Hello, world!"
    Out[40]: False
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

Top comments (0)