In this article we will explore Python string data type.
Table of Contents
- Introduction
- Create a string in Python
- Access characters from a string in Python
- Find character in a string in Python
- Slice a string in Python
- Iterate over a string in Python
- Concatenate strings in Python
- Split strings in Python
- Conclusion
Introduction
In Python, strings are immutable sequences of characters, and are used to handle textual data.
Key things you should know about strings, they are:
- ordered
- immutable
- iterable
Learning data types in each programming language is essential to understand the code and programs.
String data type is widely used in many programming and machine learning solutions built in Python specifically to store some text formatted data.
Create a string in Python
In Python, you can create a string in 4 different ways:
- By enclosing characters in single quotes
- By enclosing characters in double quotes
- By enclosing characters in triple quotes
- By using str() constructor
Create a string using single quotes
This is one of the most common ways of creating strings in Python and is very simple:
#Single quotes
my_string1 = 'Hello World!'
print(my_string1)
and you should get:
Hello World!
Create a string using double quotes
This way of creating strings in Python is identical to the previous one, except now we will be using double quotes:
#Double quotes
my_string2 = "Hello World!"
print(my_string2)
and you should get:
Hello World!
Create a string using triple quotes
This way of creating strings in Python is perhaps the most rare as there are only a few cases when we want to use it.
Enclosing characters in triple quotes will yield the same output as the previous two approaches:
#Double quotes
my_string3 = '''Hello World!'''
print(my_string3)
and you should get:
Hello World!
However, one main difference of using triple quotes is when you want to create a multiline string, where different parts of the string are on different lines in the output.
For example:
#Double quotes
my_string4 = '''Hello
World!'''
print(my_string4)
and you should get:
Hello
World!
Create a string using str() constructor
In Python, you can also create strings by using the str() constructor.
The str(object) constructor takes any object and returns its string representation.
It returns:
- String representation if object is one of the built-in Python objects (int(), float(), complex(), bool(), and others)
- Empty string if object is empty
Let’s look at a few examples of str() with different data types:
#String of int
str_int = str(5)
#String of float
str_float = str(1.5)
#String of complex
str_complex = str(1+3j)
#String of bool
str_bool = str(True)
#Print values
print(str_int)
print(str_float)
print(str_complex)
print(str_bool)
and you should get:
5
1.5
(1+3j)
True
Access characters in a string in Python
An important and very useful property of a Python string is that it’s an indexed sequence, meaning for a string with n characters, the first character will have an index = 0, second character index = 1, and all the way to n-1.
A character in a string can be accessed by its index and index can also be reversed meaning that the fist character will have an index = –n, second character index = –n+1, and all the way to -1.
To make it easier to showcase, take a look at the visualization below:
$$ \begin{matrix} \begin{array}{c|cccc} \hline \text{Index} & 0 & 1 & 2 & 3 & 4 & 5 &\\ \text{String} & P & y & t & h & o & n &\\ \text{Reversed Index} & -6 & -5 & -4 & -3 & -2 & -1 \\ \hline \end{array} \end{matrix} $$ $$\text{Length = n = 6}$$We can see that ‘P’ character in the string has two indexes: 0 and -6.
Let’s create this string in Python and print out its first character by using the indexes above:
#Create a string
my_string = 'Python'
#Print first character
print(my_string[0])
print(my_string[-6])
and you should get:
P
P
Find character in a string in Python
Using indexes we can also find the position of a character in a string.
Let’s reuse the string from the previous example: ‘Python’, and try to find the position of ‘y’ character in a string.
Using .index() method of Python string, we can find the position of a character by passing the character as a parameter into it:
#Create a string
my_string = 'Python'
#Find character
i = my_string.index('y')
#Print index
print(i)
and you should get:
1
Slice a string in Python
In the previous section we explored how to access an character from a Python string using its exact index.
In this section we will explore how to access a range of characters, for example, first two or last two.
Recall that for retrieving characters from a string using an index, we placed it in square brackets [].
Slicing is using the same approach, but instead of passing a single index value, we will pass a range.
A range in Python is passed using the following syntax [from : to].
Using ranges we can slice the string to access multiple characters:
#Create a string
my_string = 'Python'
#First two characters
first_two = my_string[:2]
#Second to fourth characters
mid_chars = my_string[1:4]
#Last two characters
last_two = my_string[-2:]
#Print characters
print(first_two)
print(mid_chars)
print(last_two)
and you should get:
Py
on
yth
Notice that characters specified at to index are not included, since in Python slicing the algorithm goes through characters until specified to index and includes all characters up to that index but not including the character under the to index.
Iterate over a string in Python
Python string is an iterable object, meaning that we can iterate over characters in the string.
Simple iteration can be performed using a for() loop:
#Create a string
my_string = 'Python'
#Iterate over a string
for char in my_string:
print(char)
and you should get:
P
y
t
h
o
n
Concatenate strings in Python
In Python, we can also concatenate (combine) multiple strings together to create a single string.
The 2 most popular ways to concatenate strings in Python are:
- Using the ‘+’ operator
- Using .join() method
Using the ‘+’ operator
Using the ‘+’ operator is one of the most commons ways to concatenate multiple strings.
Let’s take a look at an example:
#Create strings
s1 = 'Python'
s2 = 'Tutorial'
sep = ' '
#Concatenate strings
new_string = s1 + sep + s2
#Pring new string
print(new_string)
and you should get:
Python Tutorial
Using .join() method
Python string .join() method allows to concatenate a list of strings to create a new string.
The syntax of the Python string .join() method is:
separator.join([list of strings])
Let’s take a look at an example:
#Create strings
s1 = 'Python'
s2 = 'Programming'
s3 = 'Tutorial'
sep = ' '
#Concatenate strings
new_string = sep.join([s1, s2, s3])
#Pring new string
print(new_string)
and you should get:
Python Programming Tutorial
Split strings in Python
In Python, just as we can concatenate multiple strings, we can also split a single string into multiple strings.
There are multiple ways of doing it, however the most popular way is using the string .split() method, which splits a string into a list of strings based on the separator (default separator is: ‘ ‘).
The syntax of the Python string .split() method is:
string.split(separator)
Let’s take a look at an example:
#Create a string
long_string = 'Apple Banana Orange Pineapple'
#Split strings
new_strings = long_string.split()
#Print new string
print(new_strings)
and you should get:
['Apple', 'Banana', 'Orange', 'Pineapple']
You can also specify a custom separator based on what you would like to split the string.
For example:
#Create a string
long_string = 'Apple, Banana, Orange, Pineapple'
#Split string
new_strings = long_string.split(', ')
#Print new string
print(new_strings)
and you should get:
['Apple', 'Banana', 'Orange', 'Pineapple']
Conclusion
In this article we explored Python string data type including different operations you can do with strings.
As your next step in learning Python consider reading about Python data types and data structures in the following articles: