Python Strings

Python Strings

Using this guide, you will learn the fundamentals of implementing and working with Strings in the Python language. We also explore some useful techniques and function to assist you in your programming life.

Strings or string types are one of the most important data types in Python and other programming languages.

Requirements

Before proceeding with this tutorial, you will need:

  1. The latest version of Python 3 interpreter.

You can check our tutorial to learn how you install the latest version of Python 3 interpreter on your system.

What is a String?

A string or string data type used to store a sequence of characters. Although we could go deep into what characters are and how they work, let's put that aside for now.

In Python, a string refers to a sequence of Unicode characters allowing you to store a wide range of characters even in multiple languages and emojis.

How to create a String in Python?

In the Python programming language, we can create a string by enclosing the sequence of characters inside a pair of single or double quotes.

Example:

site = 'geekbits.io'
print(site)

site = "geekbits.io"
print(site)

We can run the code:

$ python3 strings.py
Output:
geekbits.io
geekbits.io
Keep in mind that you can create a string using triple quotes. However, Python formatting reserves this for docstrings or multi-line strings.

String Slicing - How to Access String Characters

Accessing individual characters within a string is known as slicing. We can use indexing format to access specific sections of a string.

Indexing in Python starts at 0. This means that the first character is at index 1, the second character at index 1 and on.

For example:

url = "https://geekbits.io"
print(url[0])

Output:

h

If you attempt to access an index that does not exists, Python will return an IndexError.

url = "https://geekbits.io"
print(url[20])
Output:
Traceback (most recent call last):
  File "/Users/geekbits/string.py", line 2, in <module>
    print(url[20])
IndexError: string index out of range

However, you can use negative indexing to access items from the element element. For example, an index -1 means that last item in the string while the index -2 means the second item from the last, etc.

Illustration

url = "https://geekbits.io"
print(url[-1])
Output:
o

Another method of accessing sections of a string is using the range operator. : . For example, we can select items from index 0 to 5 by setting the range as [0:5]

For example, to extract the protocol in a given URL, we can run;

url = "https://geekbits.io"
print(url[0:8])

Once we run the code, we should get an output as:

Output:
https://

It is good to keep in mind that slice index can only be of integer type. Hence, if you specify an index as a float, you will get a TypeError.

Example:

url = "https://geekbits.io"
print(url[1.2])

Running the code above should return an output as:

Traceback (most recent call last):
  File "/Users/geekbits/string.py", line 2, in <module>
    print(url[1.2])
TypeError: string indices must be integers

Modifying String Values

Unfortunately, in Python, strings are immutable types. This means that once a string has been assigned, its value cannot be changed.

Hence, the only way to change a string after declaration is assigning it to a new value.

Example:

# declare string
url = "http://geekbits.io"
# attempt to change string
url[0] = 'f'

In the code above, we attempt to change a string after declaration. In this case, Python will return an error as shown:

Traceback (most recent call last):
  File "/Users/geekbits/string.py", line 4, in <module>
    url[0] = 'f'
TypeError: 'str' object does not support item assignment

To resolve this, we can assign a new value to the url variable with the changes we need to apply:

# declare string
url = "http://geekbits.io"
# assign new value
url = "ftp;//geekbits.io"

Similarly, Python prevents you from delete characters from a string as shown:

url = "http://geekbits.io"
del url[0]

Output:

Traceback (most recent call last):
  File "/Users/geekbits/string.py", line 3, in <module>
    del url[0]
TypeError: 'str' object doesn't support item deletion

Python String Iteration

You can iterate through a Python string using a typical for loop. an example is as shown:

url = "http://geekbits.io"
for char in url:
    print(char)

Output:

h
t
t
p
:
/
/
g
e
e
k
b
i
t
s
.
i

Python String Formatting

There are various types of string formatting operations that can come in hand. For example, to escape quotations marks in Python, you can alternate each as shown:

string = 'He said "Tomorrow is the day"'
print(string)

Therefore, if you need to include double quotes in your string, enclose the entire string in single quotes and vice versa.

There are other escape sequences that allow you to escape various characters:

Escape Sequence Operation
\\ Escape Backslash character
\' Escape single quote character
\" Escape double quote characters
\a ASCII Bell
\b ASCII Backspace
\r ASCII Carriage Return
\f ASCII Formfeed
\n ASCII Linefeed
\t Horizontal Tab
\v Vertical Tail

Examples:

print("hello \\ me")
print('it\'s mine')
print("he said \"hello\"")
print("hi \a")
print("hello \b")
print("hello \r")
print("hello \f")
print("hello \n")
print("hello \t")
print("hello \v")

Output:

hello \ me
it's mine
he said "hello"
hi 
hello 
hello 
hello 

hello 

hello 
hello 

Python format() Function

One of the most powerful and useful function when it comes to string formatting is format() function. This function allows you to specify placeholders values in {} braces and replace them with actual values during printing.

For example:

age = 1.5
output = "GeekBits is {} months old".format(age)
print(output)

The code should return the string:

GeekBits is 1.5 months old

Useful Python String Functions

The following are some Python function that you may find useful when working with Python strings:

  • lower() - converts an input string to lowercase.
  • upper() - converts input string to uppercase.
  • split() - split a string based on a specific delimiter.
  • find() - find the index of specific substring or character within a given string.
  • replace() - replaces a specific string with a new string.

Example code:

string = "Hello, Welcome to GeekBits"
print(string.lower())
print(string.upper())
print(string.split(' '))
print(string.find('GeekBits'))
print(string.replace('Hello', 'Hi'))

Output:

hello, welcome to geekbits <- lowercase
HELLO, WELCOME TO GEEKBITS <- uppercase
['Hello,', 'Welcome', 'to', 'GeekBits'] <- split string in spaces and return a list
18 <- fetch index of the specified substring
Hi, Welcome to GeekBits <- replace specific string

Conclusion

In this article, we explored the most basic and useful commands when working python strings. You have learned how to create strings, string slicing, escape sequences, string formatting and more.

If you enjoyed this article, share it and leave us a comment below.

If you enjoy our content, please consider buying us a coffee to support our work:

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.