38. Advanced String Handling Pt. 2

  • Multiple items of information are sometimes stored on each line in a file that your program might load up. They might be separated by commas or spaces and you can easily split the lines up and re-join them once you have finished
  • Dates and product codes are frequently manipulated using these techniques
#date
date = "12/04/1981"

#Simple split function into single variables
day,month,year = date.split("/")

#Split the date into a list at (/) slash characters (alternate)
split_date = []
split_date = date.split("/")

#Grab items from split_date list
day = split_date[0]
month = split_date[1]
year = split_date[2]

#Rejoin date parts with a different delimiter (:) colon
date = day + ":" + month + ":" + year
print(date)

Tasks

  • Type in the code and test it works
  • Modify the code to accept input from the user and print the individual parts of the date
  • Modify the code to the month number with its name, and re-join the string with spaces
  • Save, print and label your code

Extension Task

The split() function will not work if the number of splits does not match the number of variables. For example:

date = "12/04"
day,month,year = date.split("/") #Won't work

Good practice would be to use a for loop/if statement construct to check the number of slashes before splitting. How might you implement this?