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]

Aching back from coding all day?

Prism Glasses

Aching back from coding all day? Try Back Problems

Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.

$ Check price
4.454.45Amazon 4 logo(128+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Learning Python

Learn to be a Pythonista! Try Python

Get a comprehensive, in-depth introduction to the core Python language with this hands-on book. Based on author Mark Lutz's popular training course, this updated fifth edition will help you quickly write efficient, high-quality code with Python. It's an ideal way to begin, whether you're new to programming or a professional developer versed in other languages.

$ Check price
64.9964.99Amazon 4 logo(279+ reviews)

More Python resources