Examples of using string indexs and the range function.
phrase = "foobar!"
# Print the first character in a string
print ("Access the first character in: " + phrase)
print(phrase[0])
print(phrase[-7])
print ("\nAccess the last character in: " + phrase)
print(phrase[6])
print(phrase[len(phrase) - 1])
print(phrase[-1])
print("\nPositive Range with Default Start Value (0)")
for value in range(5):
print(value)
print("\nPositive Range with Explicit Start Value")
for value in range(1, 5):
print(value)
print("\nPositive Range Stepping by 2")
for value in range(0, 5, 2):
print(value)
print("\nNegative Range")
for value in range(0, -5, -1):
print (value)
print("\nIndex a string with range")
test_string = "Hello World!"
for index in range(len(test_string)):
print (test_string[index])
print("\nIndex a string in reverse with range")
for index in range(len(test_string)-1, -1, -1):
print (test_string[index])
print("\nPrint the first half of a string")
for index in range(0, len(test_string)//2):
print (test_string[index])
print("\nIndex of a character in a string")
search_string = "Computer Science is Awesome!"
print(search_string.find('A'))
print("\nIndex of character NOT in a string")
print(search_string.find('Z'))
print("\nIndex of a substring in a string")
print(search_string.find('Awe'))