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
>>> "JohnDoe"
JohnDoe
>>> "John's Dough"
John's Dough
>>> 'John's Dough'
  File "<stdin>", line 1
    'John's Dough'
         ^
syntax

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)
John'sDoe
>>> name = "John'sDoe"
>>> print(name)
John'sDoe

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
'John\tDoe'
>>> 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'
'harharhar'
>>> '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'
True
>>> 'i' not in 'team'
True

Lexicographical Comparisons

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

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

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]
'E'
>>> sample[0]
'Q'
>>> 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]
'T'
>>> sample[-5]
'W'

Splicing

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]
'ER'
>>> sample[2:-1]
'ERT'
>>> sample[:5]
'QWERT'
>>> sample[2:]
'ERTY'
>>> sample[:]
'QWERTY'

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]
'QET'
>>> sample[1::2]
'WRY'

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]
'arbadacarba'

Aching back from coding all day?

Self-Massage Tool

Aching back from coding all day? Try Back Problems

Relieve spasms, tight muscles, trigger points and pressure points with the Body Back Buddy! This trigger point massage is designed to help you self-message any area of your body - especially those that are hard to reach. Keeping your muscles relaxes and out of contraction is importan in helping to reduce pain and prevent muscle injury.

$ Check price
29.9529.95Amazon 4.5 logo(3,443+ reviews)

More Back Problems resources

Learn to be a Pythonista!

Introducing Python

Learn to be a Pythonista! Try Python

Easy to understand and fun to read, Introducing Python is ideal for beginning programmers as well as those new to the language. Author Bill Lubanovic takes you from the basics to more involved and varied topics, mixing tutorials with cookbook-style code recipes to explain concepts in Python 3. End-of-chapter exercises help you practice what you learned.

$ Check price
39.9939.99Amazon 4.5 logo(37+ reviews)

More Python resources

Ad