Examples of using string indexs and the range function.
# Accessing specific characters in a string
# using the index operator
# Collections are always indexed starting with 0
# Consider the string: "foobar!"
# Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
# |---|---|---|---|---|---|---|
# Characters | f | o | o | b | a | r | ! |
# |---|---|---|---|---|---|---|
# Reverse Index | -7| -6| -5| -4| -3| -2| -1|
phrase = "foobar!"
# Print the first character in a string
print ("Access the first character in: " + phrase)
print(phrase[0])
# Can also use negative values
# starting from the far right of the string
print(phrase[-7])
# Print the last character in a string
print ("\nAccess the last character in: " + phrase)
print(phrase[6])
# THE INDEX MUST BE AN INTEGER
# FLOATING POINT WILL NOT WORK!
# Same as the example above, but uses the len
# function to get the length
print(phrase[len(phrase) - 1])
# Can also be done in reverse index
print(phrase[-1])
# Using a Range with for
print("\nPositive Range with Default Start Value (0)")
for value in range(5):
print(value)
# Range is [0, 5) and is exclusive of the
# ending value
print("\nPositive Range with Explicit Start Value")
for value in range(1, 5):
print(value)
# The third parameter to range indicates
# the step how to find the next value
# in the range
print("\nPositive Range Stepping by 2")
for value in range(0, 5, 2):
print(value)
# You can even create a negative range of values
print("\nNegative Range")
for value in range(0, -5, -1):
print (value)
# Using for and range to index a string
print("\nIndex a string with range")
test_string = "Hello World!"
for index in range(len(test_string)):
print (test_string[index])
# Using for and range to index a string
# in reverse
print("\nIndex a string in reverse with range")
for index in range(len(test_string)-1, -1, -1):
print (test_string[index])
# Range does not allow floating point values
# NOTICE THE USE OF INTEGER DIVISION (//)
print("\nPrint the first half of a string")
for index in range(0, len(test_string)//2):
print (test_string[index])
# The find function can give you the index
# of the first occurrance of a character
# or substring in a string.
print("\nIndex of a character in a string")
search_string = "Computer Science is Awesome!"
print(search_string.find('A'))
# If the character isn't in the string it returns -1
print("\nIndex of character NOT in a string")
print(search_string.find('Z'))
# Finding the beginning occurrance of a substring in
# in string.
print("\nIndex of a substring in a string")
print(search_string.find('Awe'))