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?

Acupressure Mat & Pillow

Aching back from coding all day? Try Back Problems

Relieve your stress, back, neck and sciatic pain through 1,782 acupuncture points for immediate neck pain relief. Made for lower, upper and mid chronic back pain treatment, and improves circulation, sleep, digestion and quality of life.

$$ Check price
144.87144.87Amazon 4.5 logo(1,890+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Python Playground

Learn to be a Pythonista! Try Python

Python Playground is a collection of fun programming projects that will inspire you to new heights. You'll manipulate images, build simulations, and interact with hardware using Arduino & Raspberry Pi. With each project, you'll get familiarized with leveraging external libraries for specialized tasks, breaking problems into smaller, solvable pieces, and translating algorithms into code.

$ Check price
29.9529.95Amazon 4 logo(14+ reviews)

More Python resources