banner

© 2004-21 ict4u.net

Slicing a string

Quick reference to split various parts of a string

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

stringTitle = "Minecraft"
stringSubtitle = 'Awesome Game'

stringSubtitle = 'It\'s An Awesome Game'

print(stringSubtitle)

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:{}"
    .format(stringTitle,titleLen,firstCharacter,lastCharacter))

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))