We already saw how to define strings:
s = "antidisestablishmentarianism"
(This is the longest word in the English language, according to some)
You can access elements just like in lists, with every letter behaving like an element. The result is a string of length 1.
s[0]
s[5]
You can use slicing just like with lists, but the result is a string:
s[:4]
s[5:15]
You can loop through every letter of the string:
s = "CSC180"
for letter in s:
print(letter)
You can get the length of a string using len()
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])
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 s
.
s.capitalize()
Note that calling str.capitalize()
doesn't change the value of s
:
s
str.index()
works in the same way that list.index()
does.
s.index("d")
Like with list.index()
, using str.index()
to find a substring that's not there results in an error. str.find()
is more flexible:
s.find("d")
s.find("ism")
s.find("z")
s.find(a)
returns -1
if it cannot find the index of the subtring a
in s
.
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 int
:
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[0] = "b"
would result in an error.
You can, of course, do something like this:
s = "csc180"
s = s[0] + s[1].capitalize() + s[2:]
print(s)
What happenned here is we created a new object by concatenating three strings, and then assigned that new object to s
.
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.