Wednesday, June 22, 2022

Python - Left, Right, and Middle string ranges

# Python stops right before the upper bound
# So this will print "llo"
# Character positions 2, 3, and 4
# Remember that strings start at 0

b = "Hello, World!"
print(b[2:5])

# By leaving out the starting parameter,
# we can print the first five characters
# This prints "Hello"
b = "Hello, World!"
print(b[:5])

# Conversely, if we leave out the end parameter
# we print to the end of the string
# Therefore, this prints "llo World!"

b = "Hello, World!"
print(b[2:])

# Use negatives indexes to count from the end
# to print the last character of the string
# This will print the last character (!)
b = "Hello, World!"
print(b[-1])

# This will print the "W"
print(b[-6])

# Getting fancy:
# Print from W to the end of the string
print(b[-6:])