Introduction to Python Strings

Hello and welcome to this blog post where we will learn about one of the most fundamental data types in Python: strings.

Strings are sequences of characters that can represent words, sentences, or any other textual information.

In this post, we will cover the basics of strings, how to access and manipulate their characters, how to format them with variables, and some common operations that we can perform on them.

By the end of this post, you should have a solid understanding of strings and how to work with them in Python.

Basics: What Is A String In Python

A string is a sequence of characters enclosed in quotation marks. You can use either single quotes (' ') or double quotes (" ") to create a string, as long as you are consistent. For example, these are all valid strings in Python:

'Hello'
"World"
'Python is fun'
"I'm learning strings"

A string can contain any character, including letters, numbers, symbols, spaces, and even special characters like newline (\n) or tab (\t). You can also use the backslash (\) to escape certain characters that have a special meaning in Python, such as quotation marks or backslashes themselves. For example:

'This is a \'quote\' inside a string'
"This is a \"quote\" inside a string"
"This is a backslash \ inside a string"

You can also create multi-line strings by using triple quotes (''' ''') or (""" """). This is useful when you want to write long texts or preserve the formatting of your string. For example:

'''
This is a multi-line string
that spans several lines
and preserves the indentation
'''
"""
This is another multi-line string
that does the same thing
as the previous one
"""

Accessing and Manipulating Characters

Now that we know how to create strings, let’s see how we can access and manipulate their characters.

Accessing String Characters by Indexing

One way to access a character in a string is by using indexing. Indexing means using square brackets [ ] with a number inside to specify the position of the character we want. For example:

name = 'Alice'
print(name[0]) # prints A
print(name[3]) # prints c

The index starts from 0 for the first character and goes up to the length of the string minus one for the last character. We can also use negative indices to access characters from the end of the string. For example:

name = 'Alice'
print(name[-1]) # prints e
print(name[-4]) # prints l

The index -1 corresponds to the last character and goes down to -length for the first character.

Accessing String Characters by Slicing

Another way to access characters in a string is by using slicing. Slicing means using a colon (:) inside the square brackets to specify a range of characters we want. For example:

name = 'Alice'
print(name[1:3]) # prints li
print(name[:2]) # prints Al
print(name[3:]) # prints ce

The syntax for slicing is [start:stop:step], where

  • start is the index of the first character we want,
  • stop is the index of the character after the last one we want, and
  • step is the number of characters we want to skip between each one.

If we omit any of these parameters, they default to 0 for start, length for stop, and 1 for step. Slicing returns a new string that contains the characters in the specified range.

Immutability of Python Strings

One thing to note is that strings are immutable, which means that we cannot change their characters by using indexing or slicing. For example, if we try to do something like this:

name = 'Alice'
name[0] = 'B' # this will cause an error

We will get an error saying that strings do not support item assignment.

To modify a string, we need to create a new string with the changes we want. For example, if we want to replace the first character of name with ‘B’, we can do something like this:

name = 'Alice'
new_name = 'B' + name[1:] # creates a new string 'Bl
ice'
print(new_name) # prints Bl
ice

This creates a new string by concatenating ‘B’ with the slice of name from index 1 onwards.

Methods For Manipulating Strings

Another way to manipulate strings is by using methods. Methods are functions that are associated with an object and can perform some operations on it. To call a method on a string, we use the dot (.) operator followed by the method name and parentheses (). For example:

name = 'Alice'
upper_name = name.upper() # calls the upper method on name
print(upper_name) # prints ALICE

The upper method returns a new string that has all the characters in uppercase.

There are many other methods that we can use on strings, such as lower(), capitalize(), title(), swapcase(), strip(), lstrip(), rstrip(), split(), join(), replace(), find(), index(), count(), startswith(), endswith(), and more. You can find the documentation for all the string methods here: https://docs.python.org/3/library/stdtypes.html#string-methods or by using the help() function in Python.

String Formatting

One of the most useful features of strings is that we can format them with variables. This means that we can insert values of other data types into a string and create a dynamic output.

There are several ways to format strings in Python, but one of the most convenient and modern ones is using f-strings. F-strings are formatted string literals that start with an f before the opening quote and have expressions inside curly braces {} that are evaluated at runtime. For example:

name = 'Alice'
age = 25
greeting = f'Hello, {name}. You are {age} years old.'
print(greeting) # prints Hello, Alice. You are 25 years old.

The expressions inside the curly braces can be any valid Python code, such as variables, arithmetic operations, function calls, etc. F-strings are fast, readable, and easy to use.

Another way to format strings in Python is using the format method. The format method takes a string with placeholders {} and a list of values that will replace them. For example:

name = 'Alice'
age = 25
greeting = 'Hello, {}. You are {} years old.'.format(name, age)
print(greeting) # prints Hello, Alice. You are 25 years old.

The placeholders can also have numbers inside them to specify the order of the values. For example:

name = 'Alice'
age = 25
greeting = 'Hello, {1}. You are {0} years old.'.format(age, name)
print(greeting) # prints Hello, Alice. You are 25 years old.

The format method also supports various options for formatting the values, such as alignment, padding, precision, etc. You can find the documentation for the format method here: https://docs.python.org/3/library/string.html#format-string-syntax

Common Operations

There are some common operations that we often need to perform on strings, such as searching, replacing, checking sub-strings, and comparing strings. Let’s see how we can do them in Python.

Searching for a sub-string in a string

To search for a sub-string in a string, we can use the find() or index() methods.

The find() method returns the index of the first occurrence of the sub-string in the string or -1 if not found.

The index() method does the same thing but raises an exception if not found. For example:

sentence = 'The quick brown fox jumps over the lazy dog.'
print(sentence.find('fox')) # prints 16
print(sentence.find('cat')) # prints -1
print(sentence.index('fox')) # prints 16
print(sentence.index('cat')) # raises ValueError

Replacing a sub-string in a string

To replace a sub-string in a string with another one, we can use the replace() method. The replace() method returns a new string that has all the occurrences of the old sub-string replaced with the new one. For example:

sentence = 'The quick brown fox jumps over the lazy dog.'
new_sentence = sentence.replace('fox', 'cat')
print(new_sentence) # prints The quick brown cat jumps over the lazy dog.

Startswith() and Endswith()

To check if a string contains a sub-string or starts or ends with a sub-string, we can use the in operator or the startswith() or endswith() methods. The in operator returns True if the sub-string is found in the string or False otherwise. The startswith() and endswith() methods return True if the string starts or ends with the sub-string or False otherwise. For example:

sentence = 'The quick brown fox jumps over the lazy dog.'
print('fox' in sentence) # prints True
print('cat' in sentence) # prints False
print(sentence.startswith('The')) # prints True
print(sentence.startswith('the')) # prints False
print(sentence.endswith('dog.')) # prints True
print(sentence.endswith('dog')) # prints False

Comparing two strings

To compare two strings for equality or order, we can use the == operator or the < > <= >= operators. The == operator returns True if the two strings are equal or False otherwise. The < > <= >= operators return True if the first string is less than, greater than, less than or equal to, or greater than or equal to the second string or False otherwise. The comparison is based on the lexicographical order of the characters in the strings. For example:

name1 = 'Alice'
name2 = 'Bob'
name3 = 'alice'
print(name1 == name2) # prints False
print(name1 == name3) # prints False
print(name1 < name2) # prints True
print(name1 < name3) # prints False

Conclusion

In this blog post, I have given you a brief introduction to Python strings, one of the most important and versatile data types in Python. I hope you have learned something new and useful, and that you will continue to explore and practice more with strings in Python. Happy coding!

Stephen Mclin
Stephen Mclin

Hey, I'm Steve; I write about Python and Django as if I'm teaching myself. CodingGear is sort of like my learning notes, but for all of us. Hope you'll love the content!

Articles: 125

Leave a Reply

Your email address will not be published. Required fields are marked *