03. Strings

Strings are part of Python's sequence data type, as they are a collection of characters that have an ordered to them. Strings are immutable, thus, we cannot call expressions like sample[0] = 'P' and expect our new word to start with the letter P.

Declaring strings

Strings in Python are declared by either single or double quotes. Strings are considered to be part of Python sequences, which is a data type consisting of data of a specific order.

>>> 'JohnDoe'
>>> "JohnDoe"
>>> "John's Dough"
John's Dough
>>> 'John's Dough'
  File "<stdin>", line 1
    'John's Dough'

Note how using single quotes within single quotes gives an error.

Escaping ' and "

If you want to escape a single quotation, use the backslash key (\), or use double quotations.

>>> name = 'John\'sDoe'
>>> print(name)
>>> name = "John'sDoe"
>>> print(name)

Printing strings out

You may have noticed that we can output variable contents without the print() function. The print() function is preferred, however, since this omits the enclosing quotation marks and prints special characters.

>>> name = "John\tDoe"
>>> name
>>> print(name)
John    Doe

Binary Operators

Repeating a string

Multiplying and adding strings is easy and straightforward. For example, if you want to repeat some string thrice, multiple by 3.

>>> 3 * 'har'
>>> 'hello' + ' ' + 'world'
'hello world'

Boolean operators

Additionally, we may check for certain conditions between two strings with the in and not in keywords.

>>> 'pp' in 'happiness'
>>> 'i' not in 'team'

Lexicographical Comparisons

To compare two strings lexicographically, use the one of the following operators:==, !=, <, <=, >, and >=.

>>> 'hello' >= 'hi'
>>> 'aa' == 'AA'
>>> 'aaa' > 'a'

String indexing

To extract a substring of a string, use string indexing and point to posititions with indices. Like most other programming languages, Python has a zero-based index, meaning the first character starts at 0.

>>> sample = 'QWERTY'
>>> sample[2]
>>> sample[0]
>>> sample[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Note the error when we try to access an index that is above the length of our string.

Negative indices

Negative indices may be used to count from the end of our string.

>>> sample = 'QWERTY'
>>> sample[-2]
>>> sample[-5]


We may also pull out entire substrings from a given string with given indices; this is called splicing. To specify a range, we point the index that it starts at, specify a colon (:) then up to the index the substring ends at. Thus, sample[m:n] would be from index m up to but not including index n.

>>> sample[2:4]
>>> sample[2:-1]
>>> sample[:5]
>>> sample[2:]
>>> sample[:]

Notice how we may omit one of the numbers, which will mean to go to either the beginning or end of that string. If we omit the m beginning value, then it means to take from the beginning (prefix of a string). Furthermore, if we omit the ending n value, we take it to the end (suffix of a string).

Specifying Intervals

We may also add a third parameter, to specify a step. The following would select every other letter, starting from the zeroth and first index.

>>> sample[::2]
>>> sample[1::2]

Reversing a string

To obtain the reverse of a string, simply use [::-1]. This obtains the entire string, but steps backwards from the end.

>>> "abracadabra"[::-1]

Learn to be a Pythonista!

Programming for Beginners

Learn to be a Pythonista! Try Python

This book doesn't make any assumptions about your background or knowledge of Python or computer programming. You will be guided step by step using a logical and systematic approach. As new concepts, commands, or jargon are encountered they are explained in plain language, making it easy for anyone to understand.

$ Check price
24.9924.99Amazon 4.5 logo(124+ reviews)

More Python resources

Aching back from coding all day?

Inversion Therapy Table

Aching back from coding all day? Try Back Problems

Stretch out your back and relieve your back muscles with inversion therapy. This device counteracts the forces of gravity on the body by decompressing and elongating the spine. By using this product just ten minutes a day, you can be well on your way to improved circulation and posture while relieving muscle aches, back pain and stress.

$$ Check price
119.98119.98Amazon 4.5 logo(1,700+ reviews)

More Back Problems resources