Strings

Written by Ferhawn Shaheen (8/8/2020)

Introduction

The string data type is a prominent one used in programming. It is essentially text that can be used for a variety of purposes such as user input or error messages. This lesson will discuss the string data type and some of the many ways to work with strings.

The String Data Type

A string is denoted by quotes, which can be single or double. Here is a simple example:

print("This is a string.")

# Output:
This is a string.

# This is the same but with single quotes.
print('This is another string.')

# Output:
This is another string.

While either single or double quotes work, having double quotes can help when you need an apostrophe in a string. Since an apostrophe is the same character as a single quote, Python will not know where the string ends and begins. Having double quotes prevents this from being an issue.

Strings are also immutable, meaning that they cannot be changed. If you define a variable with a string value, the string value itself cannot be appended or changed in any way like a list (these will be discussed later). This is shown in the section below.

It is worth noting that strings are not restrained to letters. Essentially all characters can become strings on a standard keyboard. This includes numbers.

Accessing Characters

In a string, one can access specific characters within it. This is through accessing the index number of a character in a string. When accessing an index, it is crucial to remember that the count starts at 0 rather than 1. This means the 5th character in a string would be referenced by [4] rather than [5].

Taking this into an example we can get the 1st character of the following string:

my_string = "Boombox"
my_string[0]

# Output:
B

# Since string aren't mutable, you cannot do the below.
# Doing so will raise a TypeError exception.
my_string[0] = "D"

It is important to note that a space in a string does count as a character. This means when counting indexes, make sure that the spaces are accounted for as separate characters.

String Splicing

In many cases, it is helpful to take segments of a string. This is known as string splicing. The format for string splicing is as follows:

# Note that the < and > signs are omitted.
my_string[<start>:<stop>:<skip>] 

In the brackets, the start is the starting index, the stop is the ending index (this does not include the ending character), and the skip is how many characters are skipped over.

String splicing returns a copy of the spliced string, which can be assigned to a variable or accepted as an argument. Here is an example of working with string splicing:

the_string = "Hello! I am the string!"

hi = the_string[0:6]
print(hi)

# Output:
Hello!

For skip, you can enter negative integers, which starts from the last character and goes backward. This essentially reverses the order.

a_string = "PAPA"
# Starting from the first index (0) and going to the last index (3), move forward
# by -1. This just results in traversal from the last index to the first, which is
# reversing the string.
print(a_string[::-1])

# Output:
APAP

String Methods

Strings have several methods that can be used to work with them. They are quite useful for a variety of tasks. Here are some examples of string methods.

my_string = "Hello"
print(my_string.upper())

# Output:
HELLO

my_string = "Hello"
print(my_string.lower())

# Output:
hello

the_string = "how can you capitalize?"
print(the_string.capitalize())

# Output:
How can you capitalize?

The outputs of these methods are quite self-explanatory. While the applications seem trivial now, they can be very useful depending on the program that is being created. .lower() is actually quite useful when comparing two strings to ignore case-sensitivity.

These are just some of the many methods available for strings. It is encouraged that you use the internet to find more methods that are tailored to a more specific purpose.

Concatenation

Concatenation is essentially combining strings with other strings or other data types. It makes use of the + operator. Note that this is not like adding and is much more like combining. Here is a simple example:

string1 = "Hello"
string2 = string1 + " Goodbye"
print(string2)

# Output:
Hello Goodbye

Typically, however, concatenation involves displaying a mix of strings and other data types such as integers. Note that the data types must be converted to a string. The following exemplifies this:

num1 = 5
num2 = 4
print("You have " + str(num1) + " apples and " + str(num2) + " oranges.")

# Output:
You have 5 apples and 4 oranges.

Notice the function str() being used. This is known as casting, where the num1 and num2 variables are being converted from integers to strings, which allows concatenation to occur. If they were still integer types, an error would be present.

Conclusion

In this lesson, strings were discussed along with important ways to work with them. Methods, concatenation, and string splicing were all discussed and incorporated. Strings are prolific in Python, and the concepts in this lesson will be applied to future lessons.

Last updated