Home      |       Contents       |       About

Prev: Numericals (Integer, Float, Complex)      |      Next: random & math modules

Strings (alphanumerics)

Strings

  • Strings are considered as ordered sequences of characters
  • String values are included in quotes (Python treats single quotes the same as double quotes)
  • The string concatenation operator is '+'
  • Integer-string multiplication: (using '*' operator) results to 'integer times string'
In [2]:
s = 'spam'
e = 'eggs'
s + e, 'spam+eggs'
Out[2]:
('spameggs', 'spam+eggs')
In [3]:
f = "foo"
s = 'spam'
boo = 2*f + " eggs " + s
boo
Out[3]:
'foofoo eggs spam'
  • Strings are a first example of a 'sequence' data structure in Python
  • Being a sequence, a string:
    • a) Has a len() function that returns the string length in characters
    • b) Is an indexed structure - Using indexes one can refer to specific string characters (we shall discuss indexing in depth in the 'list' section)
In [7]:
s = 'spam'
print(len(s))
4
  • index: a string index is an integer in [0, len(s)-1] within square brackets
In [6]:
print(s[0], s[3])
s m

Python is a zero-indexed language

  • The index of the first item in a sequence is zero '0'
  • The index of the last item in a sequence is len(s)-1
  • An index equal to len(s) returns a 'string index out of range' error
In [5]:
s[4]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-5-42efaba84d8b> in <module>()
----> 1 s[4]

IndexError: string index out of range
In [9]:
# More examples on len() and string indexes
# Before running the code try to figure out the outcome
s = 'spam'
s2 = 'spam2'
s[0], s2[len(s)], s[len(s)-1], s[len(s+'1')-len(s2)]

Further reading

. Free learning material
. See full copyright and disclaimer notice