Joseph Haugh
University of New Mexico
| s | i | l | k | s | o | n | g |
|---|---|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
We can then extract the first character from a string as follows:
s = "silksong"
first_char = s[0]
print(first_char)
We can extract multiple characters if we want to:
s = "silksong"
first_char = s[0]
second_char = s[1]
third_char = s[2]
print(first_char, second_char, third_char)
You can get the length of a string using the len() function:
s = "silksong"
print(len(s))
s[<<firstIndex>>:<<secondIndex>>]
Note that the <<secondIndex>> is exclusive
For example, we can extract the second through fifth characters with the following code:
s = "silksong"
second_to_fifth = s[1:5]
print(second_to_fifth)
What happens if the <<firstIndex>> and <<secondIndex>> are the same? Or if the <<secondIndex>> is less than the <<firstIndex>>?
Nothing is extracted! The result is empty!
You can combine two strings using the + operator:
s1 = "silk"
s2 = "song"
s = s1 + s2
print(s)
Here is how we could do it using while:
s = "silksong"
i = 0
while i < len(s):
print(s[i])
i += 1
Here is how we could do it using for and range:
s = "silksong"
for i in range(0, len(s)):
print(s[i])
We can also use a for loop without range:
s = "silksong"
for c in s:
print(c)