Python Strings

Strings are one of the most basic data types in Python, however they have dozens of functions associated with them, increasing functionality and flexibility. In order to have full control over strings in Python, you need to learn them all.

What is a String?

A string is a simple piece of text enclosed within double quotation marks. Below is an example of a string being assigned to a variable.

var = "Hello World"

String Concatenation

To “concat” means to join together. In Python, two strings can be concatenated together with the “+” operator as shown below.

var = "Hello"
var2 = "World"
var3 = var + var2
print(var3)
"Hello World"

If you want to add a number to a string, first convert it to a string.

var = "Hello world"
num = 4
print(var + str(num))
"Hello world 4"

Iterating through a string

If you haven’t studied for loops yet, you can ignore this section. This section will also be present on the for loops page for you to check out later.

a = "Hello World"
for x in a:
    print(x)

What this does is iterate through every individual character in the string and print it out. You can expect an output like this.

H
e
l
l
o

W
o
r
l
d

String Indexing

Python treats each character in a string as an individual data type. It has no data type for characters, hence a character is just a string with length 1. Python strings are thus a collection of many of these small strings, or in other words they are a “list” or “array” of characters.

Being treated as individual data types gives us greater flexibility, allowing us to access each character individually. (Remember, in Python, Indexes start from zero)