Strings are one of the most popular and arguably one of the most important data types in Python.
If you are learning Python, it’s important to understand Python Strings in detail including all kinds of operations that you can do with them.
In Python, a string is a sequence of characters. It is a data type that is enclosed in quotation marks and contains a list of characters in order including letters, numbers, symbols, and spaces among others.
In this detailed guide, we will explore the different methods for working with strings in Python. We will also take a look at some of the built-in functions that are available for working with strings.
What are Strings in Python?
A string is a sequence of characters which could include a combination of letters, numbers, whitespace, or symbol. You can think of a string as a sentence or a word or any combination of characters from your keyboard.
In real-life examples, Strings could be your username for websites, your actual name, address and so on.
Python Strings are very versatile. You can do all sorts of things with strings, such as concatenating them together, splitting them apart, and more. In the next section, we will delve into creating strings in detail and some of the basic operations you can do with strings in Python.
Creating Python Strings
In Python, you can create strings by enclosing characters in three types of quotes – single quotes (‘), double quotes (“), and triple quotes (“””).
You can use any of the three types of quotes but you must start and end with the same type of quote.
There is no limit to the number of characters you can have in a string. You can also declare strings without characters at all, which are called empty strings.
You can also have strings over multiple lines;
Here is an example of how you would create strings in Python:
my_string = "This is a string"
my_string2 = 'This is also a string'
my_string3 = """ This is a triple quoted string.
You can have multiple lines of text here."""
String indexing and slicing
Strings are sequences of characters, which means you can access them by indexing and slicing as you would with any other sequence type in Python. Indexing starts at 0 and goes to n-1, where n is the length of the string.
Next, let’s look at some of the built-in string methods and formatting operations that you can do with Python strings.
Accessing Characters in a Python String
You can access characters in a string by using square brackets [ ] and the index of the character you want to access.
It is important to note that Python starts counting indexes at 0, and not 1. So the first character in a string would be at index 0, the second character would be at index 1, and so on.
You can also use negative indexes to access characters from the end of a string. The last character in a string would be at index -1.
Here is an example of how you could access characters in a Python string:
my_string = "Hello, world!"
print (my_string)
print (my_string [-1])
print (my_string [-7])
Hello, world!
!
w
You can also use the square brackets to access a range of characters in a string, with an operation called slicing, which we will look at next.
Slicing Strings in Python
To slice a string in Python, you can use the square brackets and specify the range of characters you want to include in your new string.
The syntax for slicing strings looks like (x[2:5])
The first number within the [ ] syntax is the index of the starting character, and the second number is the index of the ending character. The number before the colon is always inclusive, and the number after the colon is always exclusive.
This means that if you want to include the 5th character in your new string, for example, then you would need to specify an ending index of 6.
Here is an example of how you could slice a string in Python:
my_string = "Hello, world!"
print (my_string)
print (my_string [-5:-2])
Hello, world!
orl
You can also leave out the starting index or the ending index, and Python will assume that you want to either start at the beginning of the string or end at the end of the string.
Here is an example of how you could do that:
my_string = "Hello, world!"
print (my_string)
print (my_string [-5:])
print (my_string [-2:])
print (my_string [-5:-2])
Hello, world!
world!
ld!
orl
Negative Indexing
Negative indexing is a feature of Python that allows you to access characters from the end of a string, instead of the beginning.
The syntax for negative indexing is (x [-1])
This means that if you want to access the last character in a string, then you would use an index of -1.
Here is an example of how you could do that:
my_string = "Hello, world!"
print (my_string)
print (my_string [-1])
Hello, world!
!
Concatenating Strings in Python
Strings can be concatenated, or combined, by using the + operator. When two strings are concatenated, the resulting string is a new string that is a combination of the two strings.
Here is an example of how you could concatenate two strings in Python:
my_string = "Hello" + ", world!"
print (my_string)
Hello, world!
You can also use the += operator to concatenate a string with another string. The += operator will take the string on the right side of the operator and add it to the end of the string on the left side of the operator.
Here is an example of how you could use the += operator to concatenate two strings:
my_string = "Hello"
my_string += ", world!"
print (my_string)
Hello, world!
f-Strings Method for Concatenating Strings
In Python 3.6 and above, you can use what is called f-strings to concatenate strings. F-strings are strings that have an f at the beginning of them (short for “formatted string literals”).
To use an f-string, put (f“string goes here”) at the beginning of the string, and then put variables inside curly braces {variable_name} wherever you want to insert them into the string.
Here is an example of how to use an f-string:
my_name = "John"
my_age = 20
print(f"Hello, my name is {my_name} and I am {my_age} years old.")
Hello, my name is John and I am 20 years old.
As you can see from the example above, using f-strings makes it much easier to concatenate variables into strings.
The format() Method for Concatenating Strings
If you are using Python 3.5 or below, then you can use the format() method to concatenate strings and variables.
The format method takes two parameters:
- The string that you want to insert the variable into
- The variable that you want to insert into the string
Here is an example of how to use the format method to concatenate a string and a variable:
my_name = "John"
my_age = 20
print("Hello, my name is {} and I am {} years old.".format(my_name, my_age))
Hello, my name is John and I am 20 years old.
As you can see from the example above, using the format method to concatenate strings and variables is a little bit more complicated than using f-strings.
Repetition in Strings – The * Operator
Strings can be repeated by using the * operator. When a string is repeated, the resulting string is a new string that is a combination of the original string repeated as many times as specified.
Here is an example of how you could repeat a string in Python:
my_string = "Hello, world! " * 3
print (my_string)
Hello, world! Hello, world! Hello, world!
String Methods
Strings in Python have a lot of built-in methods that allow you to perform various operations on them.
Here are some of the most commonly used string methods:
- len() – Returns the length of a string
- strip() – Removes whitespace from the beginning and end of a string
- lower() – Converts a string to all lowercase
- upper() – Converts a string to all uppercase
- replace() – Replaces a specified character with another character
- split() – Splits a string into an array of substrings by a specified delimiter
To use a string method, you need to specify the string you want to operate on, followed by a period, followed by the method name and any required arguments.
Here is an example of how you could use the len() string method:
my_string = "Hello, world!"
print (len(my_string))
13
my_string = "Hello, world!"
print (my_string.upper())
HELLO, WORLD!
You can see all the string methods in the official python.org documentation.
Escape Character in Strings
The backslash () is used as an escape character in Python.
When you use an escape character, the character following it is interpreted as a special character. For example, if you want to include a double-quote (“) in your string, you would need to use the backslash escape character.
If you don’t use an escape character, Python will generate an error.
Escape Sequences
Some of the most popular escape sequences include \n for Newline \t for Tab and \s – Space. There are several other escape sequences in Python including;
See Escape Characters list table
Example Use Cases of Escape Character
If you want to use quotation marks as part of the string, then you can use escape characters. An escape character is a backslash \ followed by the character you want to include in the string.
Let’s take a look at some examples.
print ("Guido said, \"Python is easy to learn!\"")
Guido said, "Python is easy to learn!"
As you can see, we were able to double quotes within the strings by using the escape character.
You can also use the escape character to include newlines in your string as well as other whitespace characters such as tabs.
Here is an example of how you would do that:
my_string = "This is a \nnewline character"
print (my_string)
This is a
newline character
If you want to use the backslash character as part of your string, then you can use two backslashes in a row. This is called an escape sequence.
Here is an example of how you could do that:
my_string = "This is a \\ backslash character"
print (my_string)
This is a \ backslash character.
FAQs – Understanding Python Strings Basics
Here are some of the frequently asked questions about Strings in Python to quickly understand the basics.
What is a string in Python?
A string is a sequence of characters in Python. Strings can be created by enclosing characters within “quotation marks”.
How to concatenate strings in python?
There are multiple ways of concatenating strings in Python. The most common way is to use the + operator. Another way is to use the format() method or f-strings.
How to use f strings in Python?
F-strings are a new way to format strings in Python. They are easier to use compared to the format() method and allow you to concatenate variables into strings more easily. To use an f-string, simply start the string with (f“string goes here”) and insert variables inside curly braces {variable_name} where you want them to appear in the string.
What’s next after Python Strings?
In this series of Python guides, we discussed the string data type in Python. We learned that strings are sequences of characters and how to create them by enclosing characters in quotes.
We also learned about string concatenation and how to index and slice strings to retrieve substrings from them.
Strings are an important part of programming in Python, so hopefully this guide has been helpful in getting you started working with them.
You can learn more about all data types in Python in this detailed guide. Continue learning about another important data type – Numerical data types in Python once you have mastered string data types.