How Strings Work In Python
A string is a sequence of characters. They are widely used in different applications to store and manipulate data and represent names, addresses, and other kinds of data that can be represented.
Strings in Python are immutable; the value is fixed. This means a new string must be created if any change is to be made. Unlike other languages like C++ and Ruby, which have mutable strings.
This article will walk you through various methods of manipulating a string in Python. It is beginner friendly, therefore, only a basic knowledge of Python is required to understand it.
How to write Python Strings
Strings can be created using single quotes, double quotes, and triple quotes.
For example:
# How to create a string using single quotes
String1 = 'Welcome to the world of kdrama'
print('This is a single quote string:')
print(String1)
# How to create a string using double quotes
String2 = "I'm a kdrama fan"
print('\nThis is a double quote string:')
print(String2)
# How to create a string using triple quotes
String3 = '''I'm a kdrama fan and I live in a world of "Delulu"'''
print('\nThis is a triple quote string:')
print(String3)
# How to create a multiline string
String4 = '''Kdrama
fan
girl'''
print('\nThis is a multiline string')
print(String4)'''
Output:
This is a single quote string:
Welcome to the world of kdrama
This is a double quote string:
I'm a kdrama fan
This is a triple quote string:
I'm a kdrama fan and i live in a world of "Delulu"
This is a multiline string
Kdrama
fan
girl
While it is okay to create a string using any of the forms given above, it is also very important to know when to use a specific form. This example shows us how to create a string and also when to use a specific form.
A few things to take note of:
\n
is a type of escape character that creates a new line when used.When a string contains an apostrophe, like in (string2). It is advisable to use a double quote.
When a string has a double quote in between, like in (string3) it is best to use a single or triple quote.
When you have a multiple-line string like in (string4), a triple quote is most appropriate
N\B: Python reads the second single or double quote in a string as the end of the string. Therefore it is important to keep these rules in mind, to save our code's readability.
String Concatenation
Strings are concatenated (added together) with the + operator and are repeated with the * operator.
For example:
add = 'Hometown ' + 2* 'cha-' + 'cha'
#'Hometown' followed by 2 times 'cha-' and 'cha'
# print
print(add)
# Output:
Hometown cha-cha-cha
Two or more string literals concatenate automatically when they’re next to each other
For example:
name = 'Home' 'town'
# print
print(name)
# Output:
Hometown
However, this feature only works with literals, not with variables or expressions. To concatenate a variable, or a variable and a literal. Use the + operator.
For example:
prefix = 'Home'
print(prefix 'town') #returns an error
print(prefix + 'town') #returns "Hometown"
Returns the following output:
print(prefix 'town')
^^^^^^
SyntaxError: invalid syntax
Hometown
In addition, we can find the length of any string by simply using the len() function. Which is one of Python's built-in functions.
For example:
prefix = 'Home'
# find the length of the string
print(len(prefix))
# Output:
4
String Index
To access individual characters in a string, the index() method is used. With the first character having index 0; a character is a string of size one. It returns the index of a substring inside the string (if found). If the substring is not found, it raises an exception.
Example:
Finding color in a string of colors
# String of colors
colors = 'yellow green red black orange'
# index of green
index_of_green = colors.index('green')
# print
print('The index of green is:', index\_of\_green)
# output:
7
The output shows that green starts at index 8 in the string of colors.
N/B: The index of this string starts at 0, and it includes special characters.
Let us play with this string a little. Imagine we wanted the color gray and not green in the string of colors. The replace() method can be used to carry out this operation. Without having to write a new string
Example:
# String of colors
colors = 'yellow green red black orange'
# Declare old and new color
old_color = 'green'
new_color = 'gray'
# Replace old color with new color
colors = colors.replace('green', new_color)
# print result
print(colors)
# Output:
yellow, gray, red, black, orange
Another string method that can come in handy is the in keyword. Imagine you have a long string of colors, and you cannot remember every color in the string. You can use the keyword in
to find colors in the string. If the color is present, it returns True, else it returns false.
Example:
colors = 'yellow green red black orange'
# find red in the string of colors
print('red' in colors)
# Output:
True
The result is True, this shows that the color red is present in the string. This is also referred to as a boolean expression because it returns a boolean value.
Indices may also be negative numbers that start counting from the right. While positive indices start from zero(0), negative indices start from -1. Because 0 and -0 are the same.
Example:
color = 'Green'
print(color[-1])
# Output:
n
String Slice
A string slice is done to obtain a substring from the given string. You can slice a string by specifying the start and end index, separated by a colon.
Example:
colors = 'yellow green red black orange'
# slice the string from index 13 to index 16
print(colors[13:16])
# Output:
red
Note the following from the above example:
The first character has an index of 0.
The character from position 4 is included.
Characters from position 10 are excluded.
There are two(2) useful slice indices:
An omitted first index defaults to zero(0).
An omitted second index defaults to the size of the string being sliced.
Example:
# String of colors
colors = 'yellow green red black orange'
# omit the start index
print(colors[:16]) #Characters from position 0 to 10 included
# Output:
yellow green red
# omit the end index
print(colors[13:]) #Characters from position 13 to the end included
# Output:
red black orange
Notice how the start is always included and the end excluded? This happens to make sure that colors[:c] + colors[c:] is always equal to colors.
Example:
colors = 'yellow green red black orange'
print(colors[:13] + colors[13:])
# Output:
yellow green red black orange
A good way to remember how slices work is to think of the indices as being in between characters. With the first edge numbered 0.
Conclusion
Python strings are a fundamental data type that allows us to manipulate and store text-based information. In this article, we have seen how to perform basic operations on strings, such as concatenation and slicing. Once you’re comfortable with the basics, it is time to dive deeper and use strings in more complex challenges.
Subscribe to my newsletter
Read articles from Victoria Burabari Poromon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Victoria Burabari Poromon
Victoria Burabari Poromon
Hi, I am Toria. I write technical articles and this is my timeline. Thank you for stopping by❤