© 2004-21

Slicing a string

Quick reference to split various parts of a string

#Author: A Knifton
#Purpose:Understand how strings work

stringTitle = "Minecraft"
stringSubtitle = 'Awesome Game'

stringSubtitle = 'It\'s An Awesome Game'


print("Understanding Strings")
# First and last
firstCharacter = stringTitle[0]
lastCharacter = stringTitle[-1]
# How long is the string?
titleLen = len(stringTitle)

#print out what we know
print ("In the string {} \n Length:{:d} First letter:{} Last letter:{}"

firstThree = stringTitle[0:3]
print("First three characters:{}".format(firstThree))

lastThree = stringTitle[-3:]
print("Last three characters:{}".format(lastThree))

# everything but the first
slice = stringTitle[1:]
print("Everything but the first:{}".format(slice))

# everything but the last
slice = stringTitle[:-1]
print("Everything but the last:{}".format(slice))