Strings

What is a string?

A string is a sequence of characters (letters, numbers and punctuation). Strings are used in programming languages to represent text and as this is a common application, there are many things you can do with strings.

What can a string do?

Quite a few things:

String Construction

Interactive session:

>>> mystring = "Peter"
>>> print mystring
Peter
>>> mystring = "a" * 4
>>> print mystring
aaaa
>>> mystring = "a" * 3 + "b"
>>> print mystring
aaab

String Access:

Interactive session:

>>> mystring = "Peter"
>>> mystring[0]
'P'
>>> mystring[3]
'e'
>>> mystring[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: string index out of range
>>> mystring[-1]
'r'

Other string operations

Length:

>>> mystring = "Peter"
>>> print len(mystring)
5

Case (capitals and small letters):

>>> mystring = "Peter"
>>> print mystring.lower()
peter
>>> print mystring.upper()
PETER

String to list:

>>> mystring = "hello there my friend"
>>> mystring.split()
['hello', 'there', 'my', 'friend']

String slicing

>>> mystring = "Peter"
>>> mystring[0:2]
Pe
>>> mystring[1:2]
e
>>> mystring[-1]
r
>>> mystring[::-1]
reteP
>>> mystring[2:]
ter

Strings and lists

Strings and lists are both sequence types, which is why many of their operations are very similar. Strings are sequences of characters, and lists can be used more generally.

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License