We already saw how to define strings:
s = "antidisestablishmentarianism"
You can access elements just like in lists, with every letter behaving like an element. The result is a string of length 1.
You can use slicing just like with lists, but the result is a string:
You can loop through every letter of the string:
s = "CSC180" for letter in s: print(letter)
C S C 1 8 0
You can get the length of a string using
s = "antidisestablishmentarianism" len(s)
This means we can also loop through strings using indices:
s = "CSC180" for i in range(len(s)): print(s[i])
C S C 1 8 0
You can use
in to check whether a string is a substring of another string:
s = "antidisestablishmentarianism" "ism" in s
"a" in s
"z" in s
There are lots of functions available for strings. See here for the full list. One example is
str.capitalize(). The value of
s.capitalize() is the capitalized version of the string
Note that calling
str.capitalize() doesn't change the value of
str.index() works in the same way that
str.index() to find a substring that's not there results in an error.
str.find() is more flexible:
-1 if it cannot find the index of the subtring
Strings are immutable -- that means that Python does not provide you with the facilities to change their contents. You can, of course, make the string
s refer to a new string:
s = "abc" s = "def" #s now refers to "def"
But then of course you could also make
s refer to an
s = 42 #s is not even a string anymore
What you cannot do is keep
s as the same object, but change its contents:
s = "b"
would result in an error.
You can, of course, do something like this:
s = "csc180" s = s + s.capitalize() + s[2:]
What happenned here is we created a new object by concatenating three strings, and then assigned that new object to
Why does it matter? It means that you cannot make a function that modifies the contents of a string:
def capitalize(s): s = s.capitalize()
Does nothing, since it reassigns a new object to a local variable.
You can, of course, write functions that return a string.